package com.mes.cloud.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mes.cloud.aop.AopContext;
import com.mes.cloud.dao.*;
import com.mes.cloud.dto.*;
import com.mes.cloud.enums.ValidatorClassEnum;
import com.mes.cloud.intercept.MetaObjectIntercept;
import com.mes.cloud.service.BcCRUDService;
import com.mes.cloud.service.ValidatorService;
import com.mes.cloud.threadlocal.JdbcContext;
import com.mes.cloud.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.*;

/**
 * @ProjectName: cloud
 * @Package: com.mes.cloud.service.impl
 * @ClassName: BcCRUDService
 * @Author: xhy
 * @Description: 获取BC表字段的服务实体
 * @Date: 2019/4/24 18:26
 * @Version: 1.0
 */
@Service
public class BcCRUDServiceImpl implements BcCRUDService {
    /**
     * 日志记录  其中在记录的时候 Class代表类名 Method代表方法名 Param代表参数
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BcCRUDServiceImpl.class);
    private static final Map MAP_VL = Maps.newHashMap();
    /**
     * 对于页面搜索的字段按照条件进行搜索的特定出来
     */
    static {
        MAP_VL.put("=","=");
        MAP_VL.put("!=","<>");
        MAP_VL.put("<=","<=");
        MAP_VL.put(">=",">=");
        MAP_VL.put(">",">");
        MAP_VL.put("<","<");
        MAP_VL.put("like","like");
        MAP_VL.put("varchar","text");
        MAP_VL.put("timestamp","date-time-picker");
        MAP_VL.put("datetime","date-time-picker");
        MAP_VL.put("date","date-picker");
        MAP_VL.put("input","input");
    }
    @Autowired
    @Qualifier("gengenJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Autowired
    @Qualifier("gengenCrmBaseJdbcTemplate")
    private JdbcTemplate gengenCrmBaseJdbcTemplate;

    @Autowired
    @Qualifier("gengenCrmCustomerJdbcTemplate")
    private JdbcTemplate gengenCrmCustomerJdbcTemplate;

    @Autowired
    @Qualifier("gengenCrmDictJdbcTemplate")
    private JdbcTemplate gengenCrmDictJdbcTemplate;

    private JdbcTemplate handTemplate;
    /**
     * 对校验接口进行初始化的预加载处理
     */
    @Autowired
    private Map<String, ValidatorService> validatorServiceMap;

    @Autowired
    private BmeBcFiledDAO bmeBcFiledDAO;
    @Autowired
    private BmeBcJoinDAO bmeBcJoinDAO;

    @Autowired
    private BmeBcSubDAO bmeBcSubDAO;

    @Autowired
    private BmeBcPickmapDAO bmeBcPickmapDAO;

    @Autowired
    private BmeBcCodeDAO bmeBcCodeDAO;

    /**
     * 通过bcname获取bc表的进本信息
     *
     * @param bcCode
     * @return
     */
    public Map getBcBase(@NotNull String bcCode)  {
        LOGGER.info("Class BCCRUDServiceImpl: Method getBcBase: InParam bcCode: {}", bcCode);
        Map map;
        try {
            map = jdbcTemplate.queryForMap(Constants.BMEBC.SELECT_BC_TABLE, bcCode);
        } catch (EmptyResultDataAccessException e) {
            map = null;
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method getBcBase: Param map：{}", map);
        return map;
    }

    /**
     * @param bcCode
     * @desc 根据对应的BCCODE以及条件获取对应的field的字段
     * @return
     */
    @Override
    public List<Map<String, Object>> findListFiled(String bcCode,Map map){
        LOGGER.info("Class BCCRUDServiceImpl: Method findListFiled: InParam bcCode: {}", bcCode);
        //实体类型默认都是数值是"Entity"代表实体，"Calculationd"代表计算，"Virtual"的表示校验。
        Map maps;
        if (map == null) {
            maps = getBcBase(bcCode);
            if (maps == null||maps.isEmpty()) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findListFiled: OutParam map==null");
                return null;
            }
            map = maps;
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(Constants.BMEBC_FILED.SELECT_BC_FILED_TABLE, map.get(Constants.ID));
        LOGGER.info("Class BCCRUDServiceImpl: Method findListFiled: OutParam list: {}", list);
        return list;
    }

    /**
     * 在已有的信息基础上获取pickmap的信息
     * @param map
     * @return
     */
    @Override
    public JSONResult getBCPickPageMapDetal(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method getBCPickPageMapDetal: map: {}", JSON.toJSON(map));
        if (map.get(Constants.VALIDATEPARAM.BCCODE) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickPageMapDetal: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        if (map.get(Constants.VALIDATEPARAM.FIELD) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickPageMapDetal: FIELD: ==null");
            return JSONResult.fail(201, "FIELD为空");
        }
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        //前端传过来的参数是数组的方式filed[a,b,c]的方式
        String inputField = map.get(Constants.VALIDATEPARAM.FIELD).toString();
        Map baseMap = getBcBase(bcName);
        if (baseMap == null || baseMap.isEmpty()) {
            return JSONResult.fail(201, "bc信息为空");
        }
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        List<Map<String, Object>> findMap = findListFiled(null,baseMap);
        if (findMap == null || findMap.isEmpty()) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickPageMapDetal: findMap == null");
            return JSONResult.fail(201, "数据字段为空,请核对参数");
        }
//        PageInfo pageInfo = new PageInfo();
        CommPager commPager = new CommPager();
        Map<String,Object> pickMap = Maps.newHashMap();
        try {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringBuffer1 = new StringBuffer();
            for (Map<String, Object> resultMap : findMap) {
                String  field = resultMap.get(Constants.VALIDATEPARAM.FIELD).toString();
                if (field.equalsIgnoreCase(inputField)){
                    pickMap = getPickMap(resultMap.get("field_pickbc").toString());
                    String pickBc = pickMap.get("pickbc").toString();
                    Map bcBase = getBcBase(pickBc);
                    String bcTable = bcBase.get(Constants.VALIDATEPARAM.BCTTABLE).toString();
                    String bc_querysql = bcBase.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
                    stringBuffer.append(bc_querysql);
                    if (!bc_querysql.toLowerCase().contains(Constants.VALIDATEPARAM.BC_WHERE) && map.size()>0) {
                        stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_6);
                    }
                    String condition = pickMap.get(Constants.VALIDATEPARAM.CONDITION).toString();
                    if (!Strings.isNullOrEmpty(stringBuffer1.toString()) && !Strings.isNullOrEmpty(condition)){
                        stringBuffer1.append(condition);
                    }else if (bc_querysql.lastIndexOf(Constants.VALIDATEPARAM.BC_WHERE_6) > bc_querysql.lastIndexOf(bcTable)&& !Strings.isNullOrEmpty(condition)){
                        stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(condition);
                    }
                    break;
                }
            }
            int countInt = stringBuffer.indexOf(" from ");
            String countSql = stringBuffer.substring(countInt);
            StringBuffer count = new StringBuffer("select count(1)");
            count.append(countSql);
            List<Object> objectList= Lists.newArrayList();
            pageTemplate(map, metaObjectIntercept, aopContext, commPager, stringBuffer, stringBuffer1, objectList, count,pickMap);
            LOGGER.info("Class BCCRUDServiceImpl: Method getBCPickPageMapDetal: total == {}");
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickPageMapDetal OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        return JSONResult.success(commPager);
    }

    /**
     * 获取sub的配置bc信息
     * @param bcCode
     * @return
     */
    @Override
    public JSONResult getBCSub(String bcCode) {
        Map bcBase = getBcBase(bcCode);
        if (bcBase==null){
            return JSONResult.fail(201,"bc信息无法获取为null");
        }
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(Constants.BME_BC_SUB.SUB_SQL, bcBase.get("id").toString());
        return JSONResult.success(mapList);
    }

    /**
     * 在已有的信息基础上获取pickmap的信息
     * @param map
     * @return
     */
    @Override
    public JSONResult getBCPickMapDetal(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method getBCPickMapDetal: map: {}", JSON.toJSON(map));
        if (map.get(Constants.VALIDATEPARAM.BCCODE) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickMapDetal: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        if (map.get(Constants.VALIDATEPARAM.FIELD) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickMapDetal: FIELD: ==null");
            return JSONResult.fail(201, "FIELD为空");
        }
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        //前端传过来的参数是数组的方式filed[a,b,c]的方式
        String inputField = map.get(Constants.VALIDATEPARAM.FIELD).toString();
        Map baseMap = getBcBase(bcName);
        if (baseMap == null || baseMap.isEmpty()) {
            return JSONResult.fail(201, "bc信息为空");
        }
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        List<Map<String, Object>> findMap = findListFiled(null,baseMap);
        if (findMap == null || findMap.isEmpty()) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickMapDetal: findMap == null");
            return JSONResult.fail(201, "数据字段为空,请核对参数");
        }
        Map<String, Object> pickMap = Maps.newHashMap();
        try {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringBuffer1 = new StringBuffer();
            pickMap = getStringObjectMap(inputField, findMap, pickMap, stringBuffer, stringBuffer1);
            stringBuffer.append(stringBuffer1);
            int  length = stringBuffer.length();
            if (stringBuffer.toString().endsWith(Constants.VALIDATEPARAM.BC_WHERE_6) ){
                stringBuffer.delete(length-6,length);
            }
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(stringBuffer.toString());
            pickMap.put("list",mapList);
            LOGGER.info("Class BCCRUDServiceImpl: Method getBCPickMapDetal: total == {}");
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCPickMapDetal OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        return JSONResult.success(pickMap);
    }
    /**
     * 根据field表获取的字段进行过滤判断是否在pickbc(即子BC内是否配置了关系)
     * 1.如果配置了关系需要将对应的SQL进行重新处理
     * 2.在处理的过程中还需要判断原SQL中的子查询是否存在对应的"where"字符 如果存在的话就不做"where"关键字的拼接了
     * 3.最终根据配置的BC对应的field表中的字段条件获取最终的BC查询SQL
     * @param inputField,findMap,pickMap,stringBuffer,stringBuffer1
     * @return
     */
    private Map<String, Object> getStringObjectMap(String inputField, List<Map<String, Object>> findMap, Map<String, Object> pickMap, StringBuffer stringBuffer, StringBuffer stringBuffer1) throws Exception {
        for (Map<String, Object> resultMap : findMap) {
            String  field = resultMap.get(Constants.VALIDATEPARAM.FIELD).toString();
            if (field.equalsIgnoreCase(inputField)){
                pickMap = getPickMap(resultMap.get("field_pickbc").toString());
                String pickBc = pickMap.get("pickbc").toString();
                Map bcBase = getBcBase(pickBc);
                String bcTable = bcBase.get(Constants.VALIDATEPARAM.BCTTABLE).toString();
                String bc_querysql = bcBase.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
                stringBuffer.append(bc_querysql);
                if (!bc_querysql.toLowerCase().contains(Constants.VALIDATEPARAM.BC_WHERE)) {
                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_6);
                }
                String condition = pickMap.get(Constants.VALIDATEPARAM.CONDITION).toString();
                if (!Strings.isNullOrEmpty(stringBuffer1.toString())&& !Strings.isNullOrEmpty(condition)){
                    stringBuffer1.append(condition);
                }else if (bc_querysql.lastIndexOf(Constants.VALIDATEPARAM.BC_WHERE_6) > bc_querysql.lastIndexOf(bcTable)&& !Strings.isNullOrEmpty(condition)){
                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(condition);
                }
                break;
            }
        }
        return pickMap;
    }
    /**
     *
     * @desc 1.对分页的出来，这个是一个复合接口，兼容分页和不分页的查询，
     *             2.对应分页的查询 前端会传对应的分页表示(pageIndex,pageSize)
     * @return
     */
    private void pageTemplate(Map<String, Object> map, MetaObjectIntercept metaObjectIntercept, AopContext aopContext,
                              CommPager commPager, StringBuffer stringBuffer, StringBuffer stringBuffer1,
                              List<Object> objectList, StringBuffer countSql,Map pickMap) throws Exception {
        int pageIndex = map.get("pageIndex") == null ? 0 : Integer.valueOf(map.get("pageIndex").toString()) == 1 ? Integer.valueOf(map.get("pageIndex").toString())-1:Integer.valueOf(map.get("pageIndex").toString());
        int pageSize = map.get("pageSize") == null ? 10 : Integer.valueOf(map.get("pageSize").toString());
        //获取分页查询对应的total的值设置到PageInfo内
        getPageTotal(commPager,pageIndex,pageSize,countSql.toString());
        stringBuffer.append(stringBuffer1);
        int subLegth = stringBuffer.length();
        //因为limit的不需要"where" 这里要进行处理下
        if (stringBuffer.toString().endsWith(Constants.VALIDATEPARAM.BC_WHERE_6) ){
            stringBuffer.delete(subLegth-6,subLegth);
        }
        stringBuffer.append(" limit ").append(pageIndex).append(",").append(pageSize);
        List<Map<String, Object>> mapList = handTemplate.queryForList(stringBuffer.toString(), objectList.toArray());
        LOGGER.info("Class BCCRUDServiceImpl: Method getBCDigital: mapList == {}",mapList);
        if (pickMap!=null){
            //如果存在pickMap的信息则需要返回给前端
            ArrayList<Object> objects = Lists.newArrayList();
            objects.add(pickMap);
            objects.add(mapList);
            commPager.setRecords(objects);
        }else {
            commPager.setRecords(mapList);
            commPager.setCurrenRecords(mapList.size());
        }
        //对拦截器进行添加参数
        if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
            metaObjectIntercept.queryAfter(aopContext);
        }
    }


    /**
     * @desc 这个是为了兼容前端的传值做的特殊处理
     * @param map
     */
    private void getRemoveMap(Map<String, Object> map) {
        if (!map.isEmpty()) {
            Iterator<String> iter = map.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                if (Constants.VALIDATEPARAM.BCCODE.equalsIgnoreCase(key)
                        || Constants.VALIDATEPARAM.PAGEINDEX.equalsIgnoreCase(key)
                        || Constants.VALIDATEPARAM.PAGESIZE.equalsIgnoreCase(key)
                        ||Constants.VALIDATEPARAM.COUNTCODE.equalsIgnoreCase(key)) {
                    iter.remove();
                }
            }
        }
    }

    /**
     * 根据pid获取对应的Digital表的信息
     *
     * @param
     * @return主要用于Digital关联查询调用
     */
    public Map<String, Object> getDigital(@NotNull String digitalCode, @NotNull String bcId) throws Exception {
        List<Map<String, Object>> list = jdbcTemplate.queryForList(Constants.Digital.SELECT_BC_DIGITAL, bcId,digitalCode);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        throw new Exception("获取Digital参数为空");
    }
    /**
     * 根据pid获取对应的Digital表的信息
     *
     * @param
     * @return主要用于Digital关联查询调用
     */
    public Map<String, Object> getPickMap(@NotNull String bcId) throws Exception {
        List<Map<String, Object>> list = jdbcTemplate.queryForList(Constants.PickMap.SELECT_BC_PICKMAP, bcId);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        throw new Exception("获取PickMap参数为空");
    }
    /**
     * @param bcName
     * @return int
     * @Description 通用的新增数据信息
     */

    @Override
    public JSONResult insert(String bcName, Map<String, Object> mapList) {

        LOGGER.info("Class BCCRUDServiceImpl: Method insert:InParam bcName : {} mapList :{}", bcName, mapList);
        Map map = getBcBase(bcName);
        if (map == null|| map.isEmpty()) {
            return JSONResult.fail(201, "获取数据异常");
        }
        initHandTemplate(map.get("bc_datasource").toString());
        List<Map<String, Object>> list = findListFiled(null,map);
        if (list == null || list.isEmpty()) {
            return JSONResult.fail(201, "获取数据异常");
        }
        //添加校验在这里进行
        String validator = valitorInputParam(mapList, list);
        if (!Strings.isNullOrEmpty(validator)) {
            return JSONResult.fail(201, validator);
        }
        //拦截器的前置处理拦截
        Map map1 = inceptBefore(map, mapList, bcName,"insert");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        String uuid = UuId.getShortUuid();
        int count = 0;
        long returnKey = 0;
        String idSlelct = "";
        boolean insertKeyFalge = true;
        JSONResult jsonResult = JSONResult.success();
        try {
            String tbName = map.get(Constants.VALIDATEPARAM.BCTTABLE).toString().trim().toLowerCase();
            StringBuffer stringBuffer = new StringBuffer("insert into " + tbName + "(");
            StringBuffer stringBuffer1 = new StringBuffer(" values(");
            List<Object> objectList = Lists.newArrayList();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> valiaMap = list.get(i);
                String fieldW = valiaMap.get(Constants.VALIDATEPARAM.FIELD).toString();
                Object extra = valiaMap.get("extra");
                String timeTl = valiaMap.get("field_type").toString();
                String clunm = valiaMap.get(Constants.VALIDATEPARAM.COLUNM).toString();
                String field_custom_type = valiaMap.get("field_custom_type").toString();
                Integer isGenerate = Integer.valueOf(valiaMap.get("is_generate").toString());
                if(!"Entity".equals(field_custom_type)){
                    continue;
                }
                Object isprikey = valiaMap.get("is_pk");
                if (!StringUtils.isEmpty(isprikey) && "PRI".equals(isprikey)) {
                    if (StringUtils.isEmpty(extra) || (!StringUtils.isEmpty(extra) && !"auto_increment".equals(extra))) {
                        stringBuffer.append("`").append(clunm).append("`,");
                        stringBuffer1.append("?,");
                        objectList.add(uuid);
                        insertKeyFalge = false;
                        continue;
                    }
                }
                //判断字段是否自动生成
                if(1 == isGenerate){
                    if(valiaMap.containsKey("code_id") && (valiaMap.get("code_id") !=null)){
                        stringBuffer.append("`").append(clunm).append("`,");
                        stringBuffer1.append("?,");
                        objectList.add(getCode(Integer.valueOf(valiaMap.get("code_id").toString())));
                        continue;
                    }

                }
                /*if (fieldW.contains("_")) {
                    fieldW = fieldW.replace("_", "");
                }*/
                fieldW = fieldW.trim();
                for (String va : mapList.keySet()) {
                    if (!mapList.containsKey(fieldW) && valiaMap.get("field_default") != null) {
                        stringBuffer.append("`").append(clunm).append("`,");
                        stringBuffer1.append("?,");
                        objectList.add(valiaMap.get("field_default"));
                        break;
                    }
                    String uP = va.trim();
                    if (fieldW.equalsIgnoreCase(uP)) {
                        stringBuffer.append("`").append(clunm).append("`,");
                        stringBuffer1.append("?,");
                        if (timeTl.equalsIgnoreCase("timestamp") || timeTl.equalsIgnoreCase("datetime")){
                            if(!StringUtils.isEmpty(mapList.get(va).toString())){
                                long timeLong = Long.parseLong(mapList.get(va).toString());
                                objectList.add(new Timestamp(timeLong));
                            }else{
                                objectList.add(null);
                            }

                        }else {
                            objectList.add(mapList.get(va));
                        }
                    }
                }
            }
            deleteChar(stringBuffer, 1, ",", true);
            deleteChar(stringBuffer1, 1, ",", true);
            String sql = stringBuffer.append(stringBuffer1).toString();
            LOGGER.info("Class BCCRUDServiceImpl: Method insert:OutParam sql : {}", sql);

            //拦截器的后置处理拦截
            if (insertKeyFalge ){
                returnKey = getInsertResultKey(sql,objectList);
                //aopContext.record.set(Constants.VALIDATEPARAM.UQID,returnKey);
                idSlelct = String.valueOf(returnKey);
            }else {
                //aopContext.record.set(Constants.VALIDATEPARAM.UQID,uuid);
                JdbcContext.getJdbcTemplate().update(sql, objectList.toArray());
                idSlelct = uuid;
            }
//            else {
//                KeyHolder keyHolder = new GeneratedKeyHolder();
//                PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() {
//                    @Override
//                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
//                        PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
//                        for(int i=0 ;i<objectList.size();i++){
//                            ps.setObject(i+1,objectList.get(i));
//                        }
//                        return ps;
//                    }
//                };
//                count = JdbcContext.getJdbcTemplate().update(preparedStatementCreator,keyHolder);
//                Number id = keyHolder.getKey();
//
//                String selectOneSql = " "+tbName+" where id='"+id+"'";
//                jsonResult.setData(JdbcContext.getJdbcTemplate().queryForMap(selectOneSql));
//            }
//            String selectOneSql = "select * from "+tbName+" where id='"+idSlelct+"'";
            String selectOneSql = "select * from (" + map.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString() + ")" + tbName+" " + "where id = '" + idSlelct + "'";
            jsonResult.setData(JdbcContext.getJdbcTemplate().queryForMap(selectOneSql));
            //对拦截器进行添加参数
            if ((!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT)) && (count > 0 || returnKey > 0))) {
                metaObjectIntercept.addSucceed(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method insert: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }finally {
            try {
                if (metaObjectIntercept!=null) {
                    metaObjectIntercept.addAfter(aopContext);
                }
            } catch (Exception e) {
                LOGGER.error("Class BCCRUDServiceImpl: Method insert finally: e :{}", e.getMessage());
                new Exception("请核对拦截配置信息");
            }
        }
        return jsonResult;
    }

    //生成code
    public String getCode(Integer codeId){
        BmeBcCodeDTO bmeBcCodeDTO = bmeBcCodeDAO.get(codeId);
        if(bmeBcCodeDTO == null){
            throw new RuntimeException("找不到code");
        }
        String dateStr = DateUtil.getCodeDate();
        String code = bmeBcCodeDTO.getPrefix()+dateStr+String.format("%04d", bmeBcCodeDTO.getCode());
        //更新code+1
        BmeBcCodeDTO bmeBcCodeDTOUpdate = new BmeBcCodeDTO();
        bmeBcCodeDTOUpdate.setId(codeId);
        bmeBcCodeDTOUpdate.setCode(bmeBcCodeDTO.getCode()+1);
        bmeBcCodeDAO.update(bmeBcCodeDTOUpdate);
        return code;
    }

    /**
     * @param bcName
     * @return int
     * @Description 通用的del数据信息
     */
    @Transactional
    @Override
    public JSONResult delete(String bcName, List ids) {
        LOGGER.info("Class BCCRUDServiceImpl: Method delete:InParam bcName : {} mapList:{}", bcName, ids);
        Map map = getBcBase(bcName);
        if (map == null || map.isEmpty()) {
            return JSONResult.fail(201, "数据异常");
        }
        initHandTemplate(map.get("bc_datasource").toString());
        Map<String, Object> incepMap = Maps.newHashMap();
        incepMap.put("bcName", bcName);
        incepMap.put("ids", ids);
        //拦截器的前置处理拦截
        Map map1 = inceptBefore(map, incepMap, "","delete");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        int count;
        try {
            String tbName = map.get(Constants.VALIDATEPARAM.BCTTABLE).toString().trim().toLowerCase();
            String updateSql = "delete from " + tbName + "  where id = ? ";
            int[] delLength = JdbcContext.getJdbcTemplate().batchUpdate(updateSql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    Object id1 = ids.get(i);
                    preparedStatement.setObject(1, id1);
                }

                @Override
                public int getBatchSize() {
                    return ids.size();
                }
            });
            if (delLength.length < 0) {
                return JSONResult.fail(201, "请核对业务数据");
            }
            count = delLength.length;
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))&& count > 0) {
                metaObjectIntercept.deleteSucceed(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method delete:InParam bcName : {} mapList:{}", bcName, ids);
            return JSONResult.fail(201, "请核对业务数据");
        }finally {
            try {
                if (metaObjectIntercept != null) {
                    metaObjectIntercept.deleteAfter(aopContext);
                }
            } catch (Exception e) {
                LOGGER.error("Class BCCRUDServiceImpl: Method insert finally: e :{}", e.getMessage());
                new Exception("请核对拦截配置信息");
            }
        }
        return JSONResult.success();
    }

    /**
     * @param paramMap
     * @return int
     * @Description 根据bc名称和对应的id进行获取对应的信息
     */
    @Override
    public JSONResult get(Map<String, Object> paramMap) {
        if (paramMap == null && paramMap.isEmpty()) {
            LOGGER.info("Class BCCRUDServiceImpl: Method get: paramMap == null");
            return JSONResult.fail(201, "参数错误");
        }
        if (!paramMap.containsKey(Constants.VALIDATEPARAM.BCCODE) || !paramMap.containsKey("id")) {
            LOGGER.info("Class BCCRUDServiceImpl: Method get: map == null");
            return JSONResult.fail(201, "参数错误");
        }
        String bcName = paramMap.get(Constants.VALIDATEPARAM.BCCODE).toString();
        Object id = paramMap.get("id");
        LOGGER.info("Class BCCRUDServiceImpl: Method get: bcName :{} id: {}" , bcName,id.toString());
        //获取BC的基本信息
        Map map = getBcBase(bcName);
        initHandTemplate(map.get("bc_datasource").toString());
        //拦截器的前置处理拦截
        Map map2 = inceptBefore(paramMap, map, "","get");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map2.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map2.get(Constants.VALIDATEPARAM.AOP);
        boolean flage =false;
        if (map == null || map.isEmpty()) {
            return JSONResult.fail(201, "获取bc信息为空");
        }
        getRemoveMap(paramMap);
        List<Object> objects = Lists.newArrayList();
        try {
            String bcSql = map.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            StringBuffer stringBuffer = new StringBuffer("select * from (");
            stringBuffer.append(bcSql).append(")T1");
            StringBuffer stringBuffer1 = new StringBuffer(Constants.VALIDATEPARAM.BC_WHERE_6);
            if (paramMap!=null){
                List<Map<String, Object>> mapList = findListFiled(null,map);
                if (mapList == null || mapList.isEmpty()) {
                    return JSONResult.fail(201, "获取数据失败请核对后再操作");
                }
                for (int i = 0; i < mapList.size(); i++) {
                    Map<String, Object> map1 = mapList.get(i);
                    for (String m : paramMap.keySet()) {
                        if (m.equals(map1.get(Constants.VALIDATEPARAM.FIELD))){
                            stringBuffer1.append("T1.").append(m).append("=? and ");
                            objects.add(paramMap.get(m));
                            flage=true;
                            break;
                        }
                    }
                    if (paramMap.size()==1 && flage){
                        break;
                    }
                }
                if (!flage){
                    return JSONResult.fail(201, "请求参数于field字段无法进行匹配,请核对参数");
                }
                deleteLengthSub(stringBuffer1);
            }
            String sql = stringBuffer.append(stringBuffer1).toString();
            Map<String, Object> mapList1 = JdbcContext.getJdbcTemplate().queryForMap(sql, objects.toArray());
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                if(metaObjectIntercept != null){
                    metaObjectIntercept.updateSucceed(aopContext);
                }
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method get: mapList1 :{}", mapList1.toString());
            return JSONResult.success(mapList1);
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method get: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }finally {
            try {
                if (metaObjectIntercept!=null) {
                    metaObjectIntercept.queryAfter(aopContext);
                }
            } catch (Exception e) {
                LOGGER.error("Class BCCRUDServiceImpl: Method insert finally: e :{}", e.getMessage());
                new Exception("请核对拦截配置信息");
            }
        }

    }

    /**
     * @param bcCode
     * @return
     */
    @Override
    public JSONResult getFiledAndFun(String bcCode) {
        LOGGER.info("Class BCCRUDServiceImpl: Method getFiledAndFun: InParam bcCode: " + bcCode);
        List<Map<String, Object>> mapList = findListFiled(bcCode,null);
        if (mapList == null || mapList.size() < 1) {
            return JSONResult.fail(201, "请核对业务数据");
        }
        List<Map<String, Object>> filedList = Lists.newArrayList();
        Map<String, Object> resultList = Maps.newHashMap();
        for (Map<String, Object> map : mapList) {
            if (map.get("name") == null || map.get(Constants.VALIDATEPARAM.FIELD) == null || map.get(Constants.VALIDATEPARAM.COLUNM) == null) {
                return JSONResult.fail(201, "请核对业务数据");
            }
            String isList = map.get("is_list").toString();
            Integer ListInt = Integer.parseInt(isList);
            if (ListInt == 1) {
                Map<String, Object> paramtMap = Maps.newHashMap();
                paramtMap.put("name", map.get("name"));
                paramtMap.put("field", map.get("field"));
                paramtMap.put("colunm", map.get("colunm"));
                filedList.add(paramtMap);
            }
        }
        resultList.put("filedList", filedList);
        //实体类型默认都是数值是"Entity"代表实体，"Calculationd"代表计算，"Virtual"的表示校验。
        Map map = getBcBase(bcCode);
        if (map == null || map.isEmpty()) {
            return JSONResult.fail(201, "请核对业务数据");
        }
        String sql = "select id,is_enable,status,name,type,ds,method,parameter,icon,pid,crtby,crtdate,updby,upddate from bme_bc_fun where pid= ? ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, map.get("id").toString());
        if (list == null || list.isEmpty()) {
            LOGGER.info("Class BCCRUDServiceImpl: Method getFiledAndFun: OutParam list==null");
            return JSONResult.fail(201, "请核对业务数据");
        }
        List<Map<String, Object>> funList = Lists.newArrayList();
        for (Map<String, Object> mapFun : list) {
            if (mapFun.get("name") == null || mapFun.get("method") == null) {
                return JSONResult.fail(201, "请核对业务数据");
            }
            Map<String, Object> funMap = Maps.newHashMap();
            funMap.put("name", mapFun.get("name"));
            funMap.put("method", mapFun.get("method"));
            funList.add(funMap);
        }
        resultList.put("funList", funList);
        LOGGER.info("Class BCCRUDServiceImpl: Method getFiledAndFun: OutParam resultList: {}", resultList);
        return JSONResult.success(resultList);
    }

    /**
     * @param bcCode
     * @return int
     * @Description 通用的del数据信息
     */

    @Override
    public JSONResult update(@NotNull String bcCode, @NotNull Map<String, Object> mapList) {
        LOGGER.info("Class BCCRUDServiceImpl: Method update: bcCode :{} mapList:{}", bcCode, mapList.toString());
        MetaObjectIntercept metaObjectIntercept = null;
        AopContext aopContext = null;
        int count;
        Map map;
        try {
            map = getBcBase(bcCode);
            if (map == null) {
                return JSONResult.fail(201, "请核对业务数据");
            }
            initHandTemplate(map.get("bc_datasource").toString());
            List<Map<String, Object>> list = findListFiled(null,map);
            //添加校验在这里进行
            String validator = valitorInputParam(mapList, list);
            if (!Strings.isNullOrEmpty(validator)) {
                return JSONResult.fail(201, validator);
            }
            //拦截器前置拦截处理
            Map map1 = inceptBefore(map, mapList, bcCode,"update");
            metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
            aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
            String tbName = map.get(Constants.VALIDATEPARAM.BCTTABLE).toString().trim().toLowerCase();
            if (list == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method update: list {}:", list);
                return JSONResult.fail(201, "请核对业务数据");
            }
            StringBuffer stringBuffer = new StringBuffer("update " + tbName + " set ");
            List<Object> objectList = Lists.newArrayList();
            Object insertId = null;
            String paramKey = null;
            int listSize = list.size();
            for (int i = 0; i < listSize; i++) {
                for (String mapl : mapList.keySet()) {
                    Map maps = list.get(i);
                    String field_custom_type = maps.get("field_custom_type").toString();
                    if(!"Entity".equals(field_custom_type)){
                        continue;
                    }
                    String fieldW = maps.get(Constants.VALIDATEPARAM.FIELD).toString();
                    /*if (fieldW.contains("_")) {
                        fieldW = fieldW.replace("_", "").trim();
                    }*/
                    if (maps.get(Constants.VALIDATEPARAM.FIELD) == null || maps.get(Constants.VALIDATEPARAM.COLUNM) == null) {
                        return JSONResult.fail(201, "关键数据字段不能为null");
                    }
                    Object isprikey = maps.get("is_pk");
                    String timeTl = maps.get("field_type").toString();
                    if ("PRI".equals(isprikey)) {
                        insertId = mapList.get(maps.get(Constants.VALIDATEPARAM.FIELD));
                        paramKey = maps.get(Constants.VALIDATEPARAM.COLUNM).toString();
                        break;
                    }
                    if (fieldW.equalsIgnoreCase(mapl.trim())) {
                        stringBuffer.append("`")
                                .append(maps.get(Constants.VALIDATEPARAM.COLUNM)).append("` = ?,");
                        if (timeTl.equalsIgnoreCase("timestamp") || timeTl.equalsIgnoreCase("datetime")){
                            if(!StringUtils.isEmpty(mapList.get(mapl).toString())){
                                long timeLong = Long.parseLong(mapList.get(mapl).toString());
                                objectList.add(new Timestamp(timeLong));
                            }else{
                                objectList.add(null);
                            }

                        }else {
                            objectList.add(mapList.get(mapl));
                        }
                        break;
                    }
                }
            }
            deleteChar(stringBuffer, 1, ",", false);
            if (insertId == null || paramKey == null) {
                return JSONResult.fail(201, "缺少重要参数,请核对后再校验");
            }
            stringBuffer.append(" where ").append(paramKey).append("= ?");
            objectList.add(insertId);
            count = JdbcContext.getJdbcTemplate().update(stringBuffer.toString(), objectList.toArray());
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT)) && count > 0) {
                metaObjectIntercept.updateSucceed(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method update: e :{}", e.getMessage());
            return JSONResult.fail(201, "更新数据操作失败");
        } finally {
            try {
                if (metaObjectIntercept != null) {
                    metaObjectIntercept.updateAfter(aopContext);
                }
            } catch (Exception e) {
                LOGGER.error("Class BCCRUDServiceImpl: Method update: e :{}", e.getMessage());
            }
        }
        return JSONResult.success();
    }

    /**
     * @param bcCode
     * @return int
     * @Description 通用的del数据信息
    {
    "condition":{"name":"wxm"},
    "value":{"name":"wxm"},
    }
     */

    @Override
    public JSONResult updateByCondition(@NotNull String bcCode, @NotNull Map<String, Object> mapList) {
        LOGGER.info("Class BCCRUDServiceImpl: Method updateByCondition: bcCode :{} mapList:{}", bcCode, mapList.toString());
        MetaObjectIntercept metaObjectIntercept = null;
        AopContext aopContext = null;
        int count;
        Map map;
        try {
            if(!mapList.containsKey("value")){
                return JSONResult.fail(201, "value不能为空");
            }
            map = getBcBase(bcCode);
            if (map == null) {
                return JSONResult.fail(201, "请核对业务数据");
            }
            initHandTemplate(map.get("bc_datasource").toString());
            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", map.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);
            if (bmeBcFiledList == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method updateByCondition: list {}:", bmeBcFiledList);
                return JSONResult.fail(201, "请核对业务数据");
            }

            //拦截器前置拦截处理
            Map map1 = inceptBefore(map, mapList, bcCode,"updateMore");
            metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
            aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
            String tbName = map.get(Constants.VALIDATEPARAM.BCTTABLE).toString().trim().toLowerCase();

            StringBuffer stringBuffer = new StringBuffer("update " + tbName + " set ");
            Map<String,Object> mapValue = (Map<String, Object>) mapList.get("value");
            //遍历需要更新的字段
            for (String fieldValueTemp : mapValue.keySet()){
                //获取字段信息
                BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList,fieldValueTemp);
                if(bmeBcFiledDTO == null){
                    continue;
                }
                if("Entity".equals(bmeBcFiledDTO.getFieldCustomType())){
                    stringBuffer.append("`").append(bmeBcFiledDTO.getColunm()).append("` = '").append(mapValue.get(fieldValueTemp)).append("',");
                }
            }
            deleteChar(stringBuffer, 1, ",", false);
            if(!mapList.containsKey("condition")){
                return JSONResult.fail(201, "condition不能为空");
            }
            String accurateSql = getAccurateSql((Map) mapList.get("condition"), bmeBcFiledList);
            stringBuffer.append(" where 1=1 ").append(accurateSql);
            count = JdbcContext.getJdbcTemplate().update(stringBuffer.toString());
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT)) && count > 0) {
                metaObjectIntercept.updateSucceed(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method update: e :{}", e.getMessage());
            return JSONResult.fail(201, "更新数据操作失败");
        } finally {
            try {
                if (metaObjectIntercept != null) {
                    metaObjectIntercept.updateAfter(aopContext);
                }
            } catch (Exception e) {
                LOGGER.error("Class BCCRUDServiceImpl: Method update: e :{}", e.getMessage());
            }
        }
        return JSONResult.success();
    }

    //获取统计数据
    //参数bcCode  digitalCode
    @Override
    public JSONResult getDigital(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method getBCDigital: map: {}", JSON.toJSON(map));
        if (map.get(Constants.VALIDATEPARAM.BCCODE) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCDigital: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        if (map.get("digitalCode")==null){
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCDigital: findMap == null");
            return JSONResult.fail(201, "数据字段为空,请核对参数");
        }
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        String digitalCode = map.get("digitalCode").toString();
        //根据BC名称获取对应的BC信息
        Map baseMap = getBcBase(bcName);
        if (baseMap == null || baseMap.isEmpty()) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        List<Map<String, Object>> mapList;
        try {
            Map<String,Object> mapDigital = getDigital(digitalCode,baseMap.get("id").toString());
            StringBuffer stringBuffer = new StringBuffer(" select ");
            //统计类型，年度，月度 year month
            String statisticsType= mapDigital.get("statistics_type").toString();

            Object bcFilter= mapDigital.get("bc_filter");
            // xAxis yAxis  X Y轴
            String configJsonStr= mapDigital.get("config_json").toString();
            JSONObject configJson = JSONObject.parseObject(configJsonStr);
            String xAxis = configJson.get("xAxis").toString();
            // 度量类型 度量字段 measureType measureField      measureType = sum count normal
            JSONArray yAxis = configJson.getJSONArray("yAxis");

            String measureSql = getMeasureSql(yAxis);
            String groupSql = getGroupSql(statisticsType,xAxis);

            stringBuffer.append(measureSql).append(",").append(groupSql).append(" as ").append(xAxis);
            stringBuffer.append(" ").append("from ");
            stringBuffer.append(baseMap.get("bc_table")).append(" ");
            if(!StringUtils.isEmpty(bcFilter)){
                stringBuffer.append(" ").append(" where ").append(bcFilter).append(" ");
            }
            stringBuffer.append(" group by ").append(groupSql);

            LOGGER.error("Class BCCRUDServiceImpl: Method getBCDigital sql :{}", stringBuffer.toString());
            mapList = JdbcContext.getJdbcTemplate().queryForList(stringBuffer.toString());

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getBCDigital OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        return JSONResult.success(mapList);
    }

    @Override
    public JSONResult my(Map<String, Object> map) {
        map.put("positionId",UserInfoUtil.getPositionId());
        return this.findPageListNew(map);
    }

    @Override
    public JSONResult myOrg(Map<String, Object> map) {
        map.put("orgId",UserInfoUtil.getOrgId());
        return this.findPageListNew(map);
    }

    @Override
    public JSONResult myTeam(Map<String, Object> map) {
        map.put("positionId",UserInfoUtil.getPositionId());
        return this.findPageListNew(map);
    }

    @Override
    public JSONResult myShare(Map<String, Object> map) {
        map.put("orgFamilyId",UserInfoUtil.getOrgFamilyId());
        return this.findPageListNew(map);
    }

    //封装group字段
    private String getGroupSql(String statisticsType,String xAxis) {
        String sql = " ";
        if("year".equals(statisticsType)){
            sql = sql + "year("+xAxis+")";

            //date_format(crtdate, '%Y%m')
        }else if("month".equals(statisticsType)){
            sql = sql + "date_format("+xAxis+", '%Y%m')";
        }
        return sql;
    }

    //封装度量字段
    private String getMeasureSql(JSONArray yAxis) {
        String sql = "";
        for(Object object : yAxis){
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            String measureType = jsonObject.get("measureType").toString();
            String measureField = jsonObject.get("measureField").toString();
            if(!sql.isEmpty()){
                sql = sql+", ";
            }
            if("normal".equals(measureType)){
                sql = sql + measureField+" ";
            }else if("count".equals(measureType)){
                sql = sql + " count(id) as  id";
            }else{
                sql = sql + measureType+"("+measureField+") as "+measureField ;
            }
        }
        return sql;
    }

    /**
     * 批量更新
     * @param bcCode
     * @param param 存放的字段和字段值
     * @param ids
     * @return
     */
    @Override
    public JSONResult batchUpdate(String bcCode, Map<String, Object> param, List<String> ids) {
        LOGGER.info("Class BCCRUDServiceImpl: Method batchUpdate: map :bcCode:{},param:{},ids{}",bcCode,param ,ids);
        if (bcCode == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method batchUpdate: bcCode: ==null");
            return JSONResult.fail(201,"bc编码为空");
        }
        //获取bc信息
        Map baseMap = getBcBase(bcCode);
        if (baseMap == null || baseMap.isEmpty()) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findList: baseMap: ==null");
            return JSONResult.fail(201, "bc信息为空,请核对业务数据");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        //获取bc所有的字段
        Map mapFiled = Maps.newHashMap();
        mapFiled.put("pid", baseMap.get(Constants.ID));
        //获取BC对应的字段
        List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

        if (bmeBcFiledList == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageList: findMap == null");
            return JSONResult.fail(201, "数据字段为空,请核对参数");
        }
        String tbName = baseMap.get(Constants.VALIDATEPARAM.BCTTABLE).toString().trim().toLowerCase();
        StringBuffer stringBuffer = new StringBuffer("update " + tbName + " set ");
        //遍历需要更新的字段
        for (String fieldValueTemp : param.keySet()){
            //获取字段信息
            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList,fieldValueTemp);
            if(bmeBcFiledDTO == null){
                continue;
            }
            if("Entity".equals(bmeBcFiledDTO.getFieldCustomType())){
                stringBuffer.append("`").append(bmeBcFiledDTO.getColunm()).append("` = '").append(param.get(fieldValueTemp)).append("',");
            }
        }
        deleteChar(stringBuffer, 1, ",", false);
        BmeBcFiledDTO priFieldBmeBcFiledDTO = getPriField(bmeBcFiledList);
        if(priFieldBmeBcFiledDTO == null){
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageList: findMap == null");
            return JSONResult.fail(201, "BC没有配置主键" );
        }
        String idsStr = org.apache.commons.lang3.StringUtils.join(ids,",");
        stringBuffer.append(" where ").append(priFieldBmeBcFiledDTO.getColunm()).append(" in (").append(idsStr).append(")");
        LOGGER.info("Class BCCRUDServiceImpl: Method batchUpdate: updateSql:{}",stringBuffer.toString());
        int count = JdbcContext.getJdbcTemplate().update(stringBuffer.toString());
        return JSONResult.success();
    }



    private BmeBcFiledDTO getPriField(List<BmeBcFiledDTO> bmeBcFiledList) {
        BmeBcFiledDTO bmeBcFiledDTO = null;
        if(CollectionUtils.isEmpty(bmeBcFiledList)){
            return bmeBcFiledDTO;
        }
        for(BmeBcFiledDTO bmeBcFiledDTOTemp : bmeBcFiledList){
            if("PRI".equals(bmeBcFiledDTOTemp.getIsPk())){
                bmeBcFiledDTO = bmeBcFiledDTOTemp;
                break;
            }
        }
        return bmeBcFiledDTO;
    }

    /**
     * @param map:执行的sql语句,falge,是否开启分页，startPage 起始页,endPage 结束页
     * @return int
     * @Description 删除bc表对于的insertBC数据
     */
    @Override
    public JSONResult findPageList(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method findPageList: map: {}", JSON.toJSON(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageList: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
//        PageInfo pageInfo = new PageInfo();
        CommPager commPager = new CommPager();
        Map baseMap = getBcBase(bcName);
        if (baseMap == null) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findPageList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        try {
            String sql = baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            List<Map<String, Object>> findMap = findListFiled(null,baseMap);
            if (findMap == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findPageList: findMap == null");
                return JSONResult.fail(201, "数据字段为空,请核对参数");
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method findPageList: findMap == {}", findMap);
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringBuffer1 = new StringBuffer();
            stringBuffer.append(sql);
            List<Object> objectList = Lists.newArrayList();
            Map copMap = Maps.newHashMap();
            copMap.putAll(map);
            getRemoveMap(map);
            String field_custom_type;
            String  appad;
            if (!map.isEmpty()) {
                if (!sql.toLowerCase().contains(Constants.VALIDATEPARAM.BC_WHERE)) {
                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_6);
                }
                String mastTable = baseMap.get(Constants.VALIDATEPARAM.BCTTABLE).toString();
                String search_value="";
                String search_term="";
                String search_field="";
                HashMap<String, String> stringMap = Maps.newHashMap();
                if (map.containsKey("search_field")){
                    search_value = map.get("search_value").toString();
                    search_term = map.get("search_term").toString();
                    search_field = map.get("search_field").toString();
                    map.put(search_field,search_value);
                    stringMap.put(search_field,search_term);
                }
                objectList = Lists.newArrayList();
                for (Map<String, Object> resultMap : findMap) {
                    String filed = resultMap.get(Constants.VALIDATEPARAM.FIELD).toString();
                    String clume = resultMap.get(Constants.VALIDATEPARAM.COLUNM).toString();
                    for (String s : map.keySet()) {
                        if (filed.equalsIgnoreCase(s) &&!Strings.isNullOrEmpty(map.get(s).toString()) ){
                            field_custom_type  = resultMap.get("field_custom_type").toString();
                            appad = Constants.FieldCustomType.CUSTOMTYPE_ENTITY.equalsIgnoreCase(field_custom_type) ? "T0."+clume : resultMap.get("field_join")+"."+clume;
                            if (Strings.isNullOrEmpty(stringBuffer1.toString()) && sql.lastIndexOf(Constants.VALIDATEPARAM.BC_WHERE_6) > sql.lastIndexOf(mastTable)) {
                                if (stringMap.containsKey(filed)){
                                    if ("like".equalsIgnoreCase(search_term)){
                                        stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(appad)
                                                .append(" ").append(search_term).append("?");
                                        objectList.add("%" + search_value + "%");
                                        break;
                                    }
                                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(appad).append(MAP_VL.get(search_term)).append("?");
                                    objectList.add(search_value);
                                    break;
                                }
                                stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(appad).append("=").append("?");
                                objectList.add(map.get(s));
                                continue;
                            }
                            if (!Strings.isNullOrEmpty(stringBuffer1.toString())) {
                                if (stringMap.containsKey(filed)) {
                                    if ("like".equalsIgnoreCase(search_term)) {
                                        stringBuffer1.append(appad)
                                                .append(" ").append(search_term).append("?");
                                        objectList.add("%" + search_value + "%");
                                        break;
                                    }
                                    stringBuffer1.append(appad).append(MAP_VL.get(search_term)).append("? and ");
                                    objectList.add(search_value);
                                    break;
                                }
                                stringBuffer1.append(appad).append("=").append("? and ");
                                objectList.add(map.get(s));
                            }
                        }
                    }
                }
                if (!Strings.isNullOrEmpty(stringBuffer1.toString())){
                    deleteLengthSub(stringBuffer1);
                }
            }
            int countInt = stringBuffer.indexOf(" from ");
            String countSql = stringBuffer.substring(countInt);
            StringBuffer count = new StringBuffer("select count(1)");
            count.append(countSql);
            pageTemplate(copMap, metaObjectIntercept, aopContext, commPager, stringBuffer, stringBuffer1, objectList, count,null);
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageList OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, "数据异常");
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method findPageList: pageInfo == {}", commPager);
        return JSONResult.success(commPager);
    }

    /**
     * 分页查询记录
     * @param map  参数格式
     *             {
    "pageIndex":1,
    "pageSize":10,
    "searchItem":[{"search_value":"asfd","search_term":"like","search_field":"username"},
    {"search_value":"asfd","search_term":"like","search_field":"id"}]

    }  分页参数 pageIndex，pageSize   searchItem过滤条件
     * @return
     */
    @Override
    public JSONResult findPageListNew(Map<String, Object> map){
        LOGGER.info("Class BCCRUDServiceImpl: Method findPageListNew: 参数: {}", JSON.toJSON(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageListNew: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        //获取bcname
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        CommPager commPager = new CommPager();
        //获取BC信息
        Map baseMap = getBcBase(bcName);
        if (baseMap == null) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findPageList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        try {
            //获取bc的sql语句
            String sql = baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", baseMap.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

            if (bmeBcFiledList == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findPageList: findMap == null");
                return JSONResult.fail(201, "数据字段为空,请核对参数");
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method findPageList: findMap == {}", bmeBcFiledList);
            //where之前的语句
            StringBuffer stringBufferBase = new StringBuffer();
            stringBufferBase.append(sql);

            //条件语句
            StringBuffer stringBufferWhere = new StringBuffer();

            //获取精确查询字段 去掉分页字段 搜索字段，其他都是精确查询字段
            Map accurateFieldMap = getAccurateField(map);

            //获取搜索字段字段 key:searchField
            List<Map> searchFieldMap = getSearchField(map);

            //获取搜索字段字段 key:orderbyField
            Map orderByFieldMap = getOrderByField(map);

            //判断是否需要where字段
            if(!accurateFieldMap.isEmpty() || !searchFieldMap.isEmpty()){
                if(baseMap.get("bc_filter") == null || baseMap.get("bc_filter").toString().isEmpty()){
                    stringBufferWhere.append(" where 1=1 ");
                }
            }

            //拼接精确匹配字段
            String accurateSql = getAccurateSql(accurateFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接模糊匹配字段
            String searchSql = getSearchSql(searchFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接排序字段
            String orderBySql = getOrderBySql(orderByFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            String selectSql = stringBufferBase.toString()+stringBufferWhere.toString()+accurateSql+searchSql;

            String countSql = "select count(*) from ("+selectSql+")A";

            selectSql = selectSql + orderBySql;

            commPager = pageTemplateNew(map,countSql,selectSql);

            List<Map<String, Object>> mapList = commPager.getRecords();

            //列表不为空，设置跨库字段值
            if(!CollectionUtils.isEmpty(mapList)){
                //获取字段中跨库字段
                List<BmeBcFiledDTO> crossJoinList = getCrossJoin(bmeBcFiledList);
                //是否有跨库字段
                if(!CollectionUtils.isEmpty(crossJoinList)){
                    for(BmeBcFiledDTO BmeBcFiledTempDTO : crossJoinList){
                        setCrossValue(mapList,BmeBcFiledTempDTO,baseMap.get(Constants.ID).toString());
                    }

                }
            }

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(baseMap.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageList OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method findPageList: pageInfo == {}", commPager);
        return JSONResult.success(commPager);
    }


    /**
     * 获取主从数据
     * @param map
     * @return
     */
    @Override
    public JSONResult findMsterSlvePageList(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method findMsterSlvePageList: 参数: {}", JSON.toJSON(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageListNew: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        //获取bcname
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        //获取BC信息
        Map baseMap = getBcBase(bcName);
        if (baseMap == null) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map<String, Object> masterMap = new HashMap<>();
        //设置主bc参数
        for(Map.Entry<String, Object> entry : map.entrySet()){
            String mapKey = entry.getKey();
            //子bc参数不需要复制
            if("subBcParam".equals(mapKey)){
                continue;
            }
            Object mapValue = entry.getValue();
            masterMap.put(mapKey,mapValue);
        }

        //获取主BC的数据
        JSONResult JSONResultMaster =  findPageListNew(map);
        if(200 != JSONResultMaster.getCode()){
            return JSONResultMaster;
        }
        //获取子BC数据
        //判断是否需要查询子BC数据
        if(!map.containsKey("subBcParam")){
            return JSONResultMaster;
        }
        //获取主BC查找的数据
        CommPager commPagerMaster = (CommPager) JSONResultMaster.getData();
        List<Map<String, Object>> mapListMaster = commPagerMaster.getRecords();
        if(CollectionUtils.isEmpty(mapListMaster)){
            return JSONResultMaster;
        }
        //获取子bc信息
        List<Map<String,Object>> subBcParam = (List<Map<String, Object>>) map.get("subBcParam");
        //没有传递子BC数据直接返回
        if(CollectionUtils.isEmpty(subBcParam)){
            return JSONResultMaster;
        }
        //遍历获取子bc数据
        for(Map<String,Object> masterMapTemp : mapListMaster){
            getSubData(masterMapTemp,subBcParam,baseMap.get("id").toString());
        }

        return JSONResultMaster;
    }

    @Override
    public JSONResult findPicmapList(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method findPicmapList: 参数: {}", JSON.toJSON(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapList: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        if (map.get("picmapCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapList: picmapCode: ==null");
            return JSONResult.fail(201, "picmapCode为空");
        }
        //获取bcname
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        List<Map<String, Object>> mapList;
        //获取BC信息
        Map bcMap = getBcBase(bcName);
        if (bcMap == null) {
            return JSONResult.fail(201, "bc信息为空");
        }
        //获取picmap信息
        Map mapPickmapParam = new HashMap();
        mapPickmapParam.put("pid",bcMap.get("id").toString());
        mapPickmapParam.put("code",map.get("picmapCode"));
        List<BmeBcPickmapDTO>  bmeBcPickmapDTOList = bmeBcPickmapDAO.getBmeBcPickmapList(mapPickmapParam);
        if(CollectionUtils.isEmpty(bmeBcPickmapDTOList)){
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapList: bmeBcPickmapDTOList: ==null");
            return JSONResult.fail(201, "bmeBcPickmapDTOList为空");
        }
        BmeBcPickmapDTO bmeBcPickmapDTOTemp = bmeBcPickmapDTOList.get(0);
        Map baseMap = getBcBase(bmeBcPickmapDTOTemp.getPickbc());
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        try {
            //获取bc的sql语句
            String sql = baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", baseMap.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

            if (bmeBcFiledList == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapList: findMap == null");
                return JSONResult.fail(201, "数据字段为空,请核对参数");
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method findPicmapList: findMap == {}", bmeBcFiledList);
            //where之前的语句
            StringBuffer stringBufferBase = new StringBuffer();
            stringBufferBase.append(sql);

            //条件语句
            StringBuffer stringBufferWhere = new StringBuffer();

            //获取精确查询字段 去掉分页字段 搜索字段，其他都是精确查询字段
            Map accurateFieldMap = getAccurateField(map);

            //获取搜索字段字段 key:searchField
            List<Map> searchFieldMap = getSearchField(map);

            //获取搜索字段字段 key:orderbyField
            Map orderByFieldMap = getOrderByField(map);

            //判断是否需要where字段
            if(!accurateFieldMap.isEmpty() || !searchFieldMap.isEmpty() || !bmeBcPickmapDTOTemp.getCondition().isEmpty()){
                if(baseMap.get("bc_filter") == null || baseMap.get("bc_filter").toString().isEmpty()){
                    stringBufferWhere.append(" where 1=1 ");
                }
            }

            //拼接精确匹配字段
            String accurateSql = getAccurateSql(accurateFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接模糊匹配字段
            String searchSql = getSearchSql(searchFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接排序字段
            String orderBySql = getOrderBySql(orderByFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            String selectSql = stringBufferBase.toString()+stringBufferWhere.toString()+accurateSql+searchSql;

            if(!bmeBcPickmapDTOTemp.getCondition().isEmpty()){
                selectSql = selectSql+" and "+bmeBcPickmapDTOTemp.getCondition();
            }
            selectSql = selectSql + orderBySql;

            mapList = JdbcContext.getJdbcTemplate().queryForList(selectSql);

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(baseMap.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapList OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, "数据异常");
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method findPicmapList: pageInfo == {}", mapList);
        return JSONResult.success(mapList);
    }

    @Override
    public JSONResult findPicmapPageList(Map<String, Object> map) {
        CommPager commPager = new CommPager();
        LOGGER.info("Class BCCRUDServiceImpl: Method findPicmapPageList: 参数: {}", JSON.toJSON(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapPageList: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        if (map.get("picmapCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapPageList: picmapCode: ==null");
            return JSONResult.fail(201, "picmapCode为空");
        }
        //获取bcname
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        List<Map<String, Object>> mapList;
        //获取BC信息
        Map bcMap = getBcBase(bcName);
        if (bcMap == null) {
            return JSONResult.fail(201, "bc信息为空");
        }
        //获取picmap信息
        Map mapPickmapParam = new HashMap();
        mapPickmapParam.put("pid",bcMap.get("id").toString());
        mapPickmapParam.put("code",map.get("picmapCode"));
        List<BmeBcPickmapDTO>  bmeBcPickmapDTOList = bmeBcPickmapDAO.getBmeBcPickmapList(mapPickmapParam);
        if(CollectionUtils.isEmpty(bmeBcPickmapDTOList)){
            LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapList: findPicmapPageList: ==null");
            return JSONResult.fail(201, "bmeBcPickmapDTOList为空");
        }
        BmeBcPickmapDTO bmeBcPickmapDTOTemp = bmeBcPickmapDTOList.get(0);
        Map baseMap = getBcBase(bmeBcPickmapDTOTemp.getPickbc());
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        try {
            //获取bc的sql语句
            String sql = baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", baseMap.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

            if (bmeBcFiledList == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findPicmapPageList: findMap == null");
                return JSONResult.fail(201, "数据字段为空,请核对参数");
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method findPicmapPageList: findMap == {}", bmeBcFiledList);
            //where之前的语句
            StringBuffer stringBufferBase = new StringBuffer();
            stringBufferBase.append(sql);

            //条件语句
            StringBuffer stringBufferWhere = new StringBuffer();

            //获取精确查询字段 去掉分页字段 搜索字段，其他都是精确查询字段
            Map accurateFieldMap = getAccurateField(map);

            //获取搜索字段字段 key:searchField
            List<Map> searchFieldMap = getSearchField(map);

            //获取搜索字段字段 key:orderbyField
            Map orderByFieldMap = getOrderByField(map);

            //判断是否需要where字段
            if(!accurateFieldMap.isEmpty() || !searchFieldMap.isEmpty() || !bmeBcPickmapDTOTemp.getCondition().isEmpty()){
                if(baseMap.get("bc_filter") == null || baseMap.get("bc_filter").toString().isEmpty()){
                    stringBufferWhere.append(" where 1=1 ");
                }
            }

            //拼接精确匹配字段
            String accurateSql = getAccurateSql(accurateFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接模糊匹配字段
            String searchSql = getSearchSql(searchFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接排序字段
            String orderBySql = getOrderBySql(orderByFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            String selectSql = stringBufferBase.toString()+stringBufferWhere.toString()+accurateSql+searchSql;

            if(!bmeBcPickmapDTOTemp.getCondition().isEmpty()){
                selectSql = selectSql+" and "+bmeBcPickmapDTOTemp.getCondition();
            }

            String countSql = "select count(*) from ("+selectSql+")A";

            selectSql = selectSql + orderBySql;

            commPager = pageTemplateNew(map,countSql,selectSql);

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(baseMap.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findPageList OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, "数据异常");
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method findPageList: pageInfo == {}", commPager);
        return JSONResult.success(commPager);
    }

    /**
     *
     * @param masterMapTemp  主BC记录信息
     * @param subBcParam   从BC信息
     */
    private void getSubData(Map<String, Object> masterMapTemp, List<Map<String, Object>> subBcParam,String pid) {
        for(Map<String, Object> subMap : subBcParam){
            //从BC字段
            String subBcCode = subMap.get("subBcCode").toString();
            if(subBcCode.isEmpty()){
                continue;
            }
            Map<Object, Object> bmeBcSubDTOParam = new HashMap<>();
            bmeBcSubDTOParam.put("pid",pid);
            bmeBcSubDTOParam.put("subName",subBcCode);
            List<BmeBcSubDTO> bmeBcSubDTOList = bmeBcSubDAO.getBmeBcSubList(bmeBcSubDTOParam);
            if(CollectionUtils.isEmpty(bmeBcSubDTOList)){
                continue;
            }
            BmeBcSubDTO bmeBcSubDTO = bmeBcSubDTOList.get(0);
            String subField = bmeBcSubDTO.getSubField();
            String subName = bmeBcSubDTO.getSubName();
            String bcField = bmeBcSubDTO.getBcField();
            Object bcFieldValue = masterMapTemp.get(bcField);
            if(subField.isEmpty() || subName.isEmpty() || bcField.isEmpty() || bcFieldValue == null){
                continue;
            }
            //设置从bc参数
            Map<String, Object> slveMap = new HashMap<>();
            for(Map.Entry<String, Object> entry : subMap.entrySet()){
                String mapKey = entry.getKey();
                //子bc参数不需要复制
                if("subBcCode".equals(mapKey)){
                    continue;
                }
                Object mapValue = entry.getValue();
                slveMap.put(mapKey,mapValue);
            }
            slveMap.put(subField,bcFieldValue);
            slveMap.put(Constants.VALIDATEPARAM.BCCODE,subName);
            JSONResult JSONResultSlve =  findPageListNew(slveMap);
            if(200 != JSONResultSlve.getCode()){
                continue;
            }
            masterMapTemp.put(subName+"list",JSONResultSlve.getData());
        }
    }


    private Map getOrderByField(Map<String, Object> map) {
        Map orderByFieldMap = new HashMap();
        if (map.isEmpty()) {
            return orderByFieldMap;
        }
        if(!map.containsKey(Constants.VALIDATEPARAM.ORDERBYFIELD)){
            return orderByFieldMap;
        }
        return (Map) map.get(Constants.VALIDATEPARAM.ORDERBYFIELD);
    }

    /**
     * 分页
     * @param map
     * @param countSql
     * @param selectSql
     * @return
     */
    private CommPager pageTemplateNew(Map<String, Object> map, String countSql, String selectSql) {
        CommPager commPager = new CommPager();
        int pageIndex = map.get("pageIndex") == null ? 1 : Integer.valueOf(map.get("pageIndex").toString());
        int pageSize = map.get("pageSize") == null ? 10 : Integer.valueOf(map.get("pageSize").toString());
        //获取分页查询对应的total的值设置到PageInfo内
        LOGGER.info("Class BCCRUDServiceImpl: Method pageTemplateNew: countSql ={}",countSql);
        if(pageIndex < 1){
            pageIndex = 1;
        }
        int startIndex = (pageIndex-1)*pageSize;
        getPageTotal(commPager,pageIndex,pageSize,countSql);
        selectSql = selectSql +" limit "+startIndex+","+pageSize;
        LOGGER.info("Class BCCRUDServiceImpl: Method pageTemplateNew: selectSql ={}",selectSql);
        List<Map<String, Object>> mapList = JdbcContext.getJdbcTemplate().queryForList(selectSql);
        LOGGER.info("Class BCCRUDServiceImpl: Method pageTemplateNew: mapList == {}",mapList);
        commPager.setRecords(mapList);
        commPager.setCurrenRecords(mapList.size());
        return commPager;
    }


    /**
     * 获取精确匹配sql
     * @param accurateFieldMap 需要精确匹配的字段-值
     * @param bmeBcFiledList  bc下的字段
     * @return
     */
    private String getAccurateSql(Map accurateFieldMap, List<BmeBcFiledDTO> bmeBcFiledList,String bcId) {
        StringBuffer accurateSql = new StringBuffer();
        if(accurateFieldMap.isEmpty()){
            return accurateSql.toString();
        }
        Iterator<String> iter = accurateFieldMap.keySet().iterator();
        while (iter.hasNext()) {
            //key对应 bme_bc_filed表field字段值
            String searchField = iter.next();
            //用field获取字段详情
            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList,searchField);
            if(bmeBcFiledDTO == null){
                continue;
            }
            //判断字段类型 如果是entity 直接用TO.做拼接
           if("Entity".equals(bmeBcFiledDTO.getFieldCustomType())){
                if(!accurateFieldMap.get(searchField).toString().isEmpty()){
                    accurateSql.append(" and T0.").append(bmeBcFiledDTO.getColunm()).append("='").append(accurateFieldMap.get(searchField)).append("'");
                }

           }
            //如果是关联表 需要找到关联表的别名
            if("Join".equals(bmeBcFiledDTO.getFieldCustomType())){
                Map<Object, Object> joinParams = new HashMap<>();
                joinParams.put("joinName",bmeBcFiledDTO.getFieldJoin());
                joinParams.put("pid",bcId);
                BmeBcJoinDTO bmeBcJoinDTO = bmeBcJoinDAO.getBmeBcJoinByIdName(joinParams);
                if(bmeBcJoinDTO == null){
                    continue;
                }
                if(!accurateFieldMap.get(searchField).toString().isEmpty()){
                    accurateSql.append(" and ").append(bmeBcJoinDTO.getJoinMasterAlias()).append(".").append(bmeBcFiledDTO.getColunm()).append("='").append(accurateFieldMap.get(searchField)).append("'");
                }

            }
        }
        return accurateSql.toString();
    }


    /**
     * 获取精确匹配sql
     * @param accurateFieldMap 需要精确匹配的字段-值
     * @param bmeBcFiledList  bc下的字段
     * @return
     */
    private String getAccurateSql(Map accurateFieldMap, List<BmeBcFiledDTO> bmeBcFiledList) {
        StringBuffer accurateSql = new StringBuffer();
        if (accurateFieldMap.isEmpty()) {
            return accurateSql.toString();
        }
        Iterator<String> iter = accurateFieldMap.keySet().iterator();
        while (iter.hasNext()) {
            //key对应 bme_bc_filed表field字段值
            String searchField = iter.next();
            //用field获取字段详情
            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList, searchField);
            if (bmeBcFiledDTO == null) {
                continue;
            }
            //判断字段类型 如果是entity 直接用TO.做拼接
            if ("Entity".equals(bmeBcFiledDTO.getFieldCustomType())) {
                if (!accurateFieldMap.get(searchField).toString().isEmpty()) {
                    accurateSql.append(" and ").append(bmeBcFiledDTO.getColunm()).append("='").append(accurateFieldMap.get(searchField)).append("'");
                }

            }

        }
        return accurateSql.toString();
    }

    /**
     *
     * @param bmeBcFiledList
     * @param key
     * @return
     */
    private BmeBcFiledDTO getFieldMap(List<BmeBcFiledDTO> bmeBcFiledList, String key) {
        BmeBcFiledDTO bmeBcFiledDTOR = null;
        if(CollectionUtils.isEmpty(bmeBcFiledList)){
            return bmeBcFiledDTOR;
        }
        if(StringUtils.isEmpty(key)){
            return bmeBcFiledDTOR;
        }
        for(BmeBcFiledDTO bmeBcFiledDTO : bmeBcFiledList){
            if(key.equals(bmeBcFiledDTO.getField())){
                bmeBcFiledDTOR = bmeBcFiledDTO;
                break;
            }
        }
        return bmeBcFiledDTOR;
    }

    /**
     * 获取模糊匹配sql
     * @param searchFieldMapList
     * @param bmeBcFiledList
     * @param bcId
     * @return
     */
    private String getSearchSql(List<Map> searchFieldMapList, List<BmeBcFiledDTO> bmeBcFiledList,String bcId) {
        StringBuffer searchSql = new StringBuffer();
        if(searchFieldMapList.isEmpty()){
            return searchSql.toString();
        }
        for (int i = 0; i < searchFieldMapList.size(); i++) {
            Map mapTemp = searchFieldMapList.get(i);
            //key对应 bme_bc_filed表field字段值
            String searchField = mapTemp.get("search_field").toString();
            String searchValue = mapTemp.get("search_value").toString();
            String searchTerm = mapTemp.get("search_term").toString();
            String searchLink = "and";
            if (mapTemp.containsKey("search_link")) {
                searchLink = mapTemp.get("search_link").toString();
            }
            //用field获取字段详情
            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList,searchField);
            if(bmeBcFiledDTO == null){
                continue;
            }

            if(searchValue.isEmpty()){
                continue;
            }
            //拼接and -or
            if(i != 0){
                searchSql.append(" ").append(searchLink).append(" ");
            }
            //判断字段类型 如果是entity 直接用TO.做拼接
            if ("Entity".equals(bmeBcFiledDTO.getFieldCustomType())) {
                searchSql.append(" T0.").append(bmeBcFiledDTO.getColunm()).append(" ");
                searchSql.append(MAP_VL.get(searchTerm));
                if ("like".equals(searchTerm)) {
                    searchSql.append(" '%").append(searchValue).append("%'");
                } else {
                    searchSql.append(" '").append(searchValue).append("'");
                }

            }
            //如果是关联表 需要找到关联表的别名
            if ("Join".equals(bmeBcFiledDTO.getFieldCustomType())) {
                Map<Object, Object> joinParams = new HashMap<>();
                joinParams.put("joinName", bmeBcFiledDTO.getFieldJoin());
                joinParams.put("pid", bcId);
                BmeBcJoinDTO bmeBcJoinDTO = bmeBcJoinDAO.getBmeBcJoinByIdName(joinParams);
                if (bmeBcJoinDTO == null) {
                    continue;
                }
                searchSql.append(bmeBcJoinDTO.getJoinSlaveAlias()).append(".").append(bmeBcFiledDTO.getColunm()).append(" ");
                searchSql.append(MAP_VL.get(searchTerm));
                if ("like".equals(searchTerm)) {
                    searchSql.append(" '%").append(searchValue).append("%'");
                } else {
                    searchSql.append(" '").append(searchValue).append("'");
                }
            }
        }
        String returnSearchSql = "";
        if(!searchSql.toString().isEmpty()){
            returnSearchSql = " and ("+searchSql.toString()+")";
        }
        return returnSearchSql;
    }

    private String getOrderBySql(Map orderByFieldMap, List<BmeBcFiledDTO> bmeBcFiledList, String bcId) {
        StringBuffer orderBySql = new StringBuffer();
        if(orderByFieldMap.isEmpty()){
            return orderBySql.toString();
        }
        orderBySql.append(" order by ");
        Iterator<String> iter = orderByFieldMap.keySet().iterator();
        while (iter.hasNext()) {
            //key对应 bme_bc_filed表field字段值
            String orderByField = iter.next();
            //用field获取字段详情
            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList,orderByField);
            if(bmeBcFiledDTO == null){
                continue;
            }
            //判断字段类型 如果是entity 直接用TO.做拼接
            if("Entity".equals(bmeBcFiledDTO.getFieldCustomType())){
                if(!orderByFieldMap.get(orderByField).toString().isEmpty()){
                    orderBySql.append("  T0.").append(bmeBcFiledDTO.getColunm()).append(" ").append(orderByFieldMap.get(orderByField)).append(",");
                }
            }
            //如果是关联表 需要找到关联表的别名
            if("Join".equals(bmeBcFiledDTO.getFieldCustomType())){
                Map<Object, Object> joinParams = new HashMap<>();
                joinParams.put("joinName",bmeBcFiledDTO.getFieldJoin());
                joinParams.put("pid",bcId);
                BmeBcJoinDTO bmeBcJoinDTO = bmeBcJoinDAO.getBmeBcJoinByIdName(joinParams);
                if(bmeBcJoinDTO == null){
                    continue;
                }
                if(!orderByFieldMap.get(orderByField).toString().isEmpty()){
                    orderBySql.append(bmeBcJoinDTO.getJoinSlaveAlias()).append(".").append(bmeBcFiledDTO.getColunm()).append(" ").append(orderByFieldMap.get(orderByField)).append(",");
                }
            }
        }
        deleteChar(orderBySql, 1, ",", false);
        return orderBySql.toString();
    }


    /**
     * 获取精确匹配字段
     * @param map
     * @return
     */
    private Map getAccurateField(Map<String, Object> map) {
        Map accurateFieldMap = new HashMap();
        if (!map.isEmpty()) {
            Iterator<String> iter = map.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                if (Constants.VALIDATEPARAM.BCCODE.equalsIgnoreCase(key)
                        || Constants.VALIDATEPARAM.PAGEINDEX.equalsIgnoreCase(key)
                        || Constants.VALIDATEPARAM.PAGESIZE.equalsIgnoreCase(key)
                        ||Constants.VALIDATEPARAM.COUNTCODE.equalsIgnoreCase(key)
                        ||Constants.VALIDATEPARAM.SEARCHFIELD.equalsIgnoreCase(key)
                        ||Constants.VALIDATEPARAM.ORDERBYFIELD.equalsIgnoreCase(key)) {
                    continue;
                }
                accurateFieldMap.put(key,map.get(key));

            }
        }
        return accurateFieldMap;
    }

    /**
     * 获取模糊匹配字段
     * @param map
     * @return
     */
    private List<Map> getSearchField(Map<String, Object> map) {
        List<Map> searchFieldMap = new ArrayList<>();
        if (map.isEmpty()) {
            return searchFieldMap;
        }
        if(!map.containsKey(Constants.VALIDATEPARAM.SEARCHFIELD)){
            return searchFieldMap;
        }
        return (List<Map>) map.get(Constants.VALIDATEPARAM.SEARCHFIELD);
    }

    private void deleteLengthSub(StringBuffer stringBuffer1) {
        int sbLength = stringBuffer1.lastIndexOf(Constants.VALIDATEPARAM.BC_WHERE_AND);
        if (sbLength == stringBuffer1.length() - 5) {
            stringBuffer1.delete(sbLength, stringBuffer1.length());
        }
    }

    /**
     * 获取分页的total值
     * @param commPager
     * @param pageIndex
     * @param pageSize
     * @param countSql
     */
    private void getPageTotal(CommPager commPager, int pageIndex, int pageSize, String countSql) {
        int total = JdbcContext.getJdbcTemplate().queryForObject(countSql, Integer.TYPE);
        commPager.setPageSize(pageSize);
        commPager.setPageIndex(pageIndex);
        int pages = (int) Math.ceil(1.0 * total / pageSize);
        commPager.setTotalRecord(total);
        commPager.setTotalPage(pages);

    }

    /**
     * @param map:执行的sql语句,falge,是否开启分页，startPage 起始页,endPage 结束页
     * @return int
     * @Description 删除bc表对于的insertBC数据
     */
    @Override
    public JSONResult findList(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method findList: map :{}", JSON.toJSONString(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findList: bcCode: ==null");
            return JSONResult.fail(201,"bc编码为空");
        }
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        List<Map<String, Object>> mapList;
        Map baseMap = getBcBase(bcName);
        if (baseMap == null || baseMap.isEmpty()) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findList: baseMap: ==null");
            return JSONResult.fail(201, "bc信息为空,请核对业务数据");
        }
        if (baseMap.get("bc_querysql") == null || baseMap.isEmpty()) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findList OutParam: bc_querysql == null");
            return JSONResult.fail(201, "sql信息为空,请先获取sql数据");
        }
        initHandTemplate(map.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        try {
            String sql = baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            String mastTable = baseMap.get(Constants.VALIDATEPARAM.BCTTABLE).toString();
            List<Map<String, Object>> findMap = findListFiled(null,baseMap);
            if (findMap == null || findMap.isEmpty()) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findList findMap  == null");
                return JSONResult.fail(201, "bc字段信息为空");
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method findList findMap  == {}", JSON.toJSONString(findMap));
            StringBuffer strBuffer = new StringBuffer();
            List<Object> objList = Lists.newArrayList();
            strBuffer.append(sql);
            getRemoveMap(map);
            if (!map.isEmpty()){
                getMapCondict(map, sql, mastTable, findMap,strBuffer, objList);
            }
            mapList = JdbcContext.getJdbcTemplate().queryForList(strBuffer.toString(), objList.toArray());
            if (mapList == null || mapList.isEmpty()) {
                LOGGER.info("Class BCCRUDServiceImpl: Method findList OutParam: mapList == null");
            }
            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(baseMap.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findList OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, "数据异常");
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method findList mapList  == {}", JSON.toJSONString(mapList));
        return JSONResult.success(mapList);
    }


    /**
     * @param map:执行的sql语句,falge,是否开启分页，startPage 起始页,endPage 结束页
     * @return int
     * @Description 删除bc表对于的insertBC数据
     */
    @Override
    public JSONResult findListNew(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method findListNew: 参数: {}", JSON.toJSON(map));
        if (map.get("bcCode") == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findListNew: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }
        //获取bcname
        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();
        List<Map<String, Object>> mapList;
        //获取BC信息
        Map baseMap = getBcBase(bcName);
        if (baseMap == null) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "","findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);
        try {
            //获取bc的sql语句
            String sql = baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", baseMap.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

            if (bmeBcFiledList == null) {
                LOGGER.error("Class BCCRUDServiceImpl: Method findListNew: findMap == null");
                return JSONResult.fail(201, "数据字段为空,请核对参数");
            }
            LOGGER.info("Class BCCRUDServiceImpl: Method findListNew: findMap == {}", bmeBcFiledList);
            //where之前的语句
            StringBuffer stringBufferBase = new StringBuffer();
            stringBufferBase.append(sql);

            //条件语句
            StringBuffer stringBufferWhere = new StringBuffer();

            //获取精确查询字段 去掉分页字段 搜索字段，其他都是精确查询字段
            Map accurateFieldMap = getAccurateField(map);

            //获取搜索字段字段 key:searchField
            List<Map> searchFieldMap = getSearchField(map);

            //获取搜索字段字段 key:orderbyField
            Map orderByFieldMap = getOrderByField(map);

            //判断是否需要where字段
            if(!accurateFieldMap.isEmpty() || !searchFieldMap.isEmpty()){
                if(baseMap.get("bc_filter") == null || baseMap.get("bc_filter").toString().isEmpty()){
                    stringBufferWhere.append(" where 1=1 ");
                }
            }

            //拼接精确匹配字段
            String accurateSql = getAccurateSql(accurateFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接模糊匹配字段
            String searchSql = getSearchSql(searchFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            //拼接排序字段
            String orderBySql = getOrderBySql(orderByFieldMap,bmeBcFiledList,baseMap.get(Constants.ID).toString());

            String selectSql = stringBufferBase.toString()+stringBufferWhere.toString()+accurateSql+searchSql;

            selectSql = selectSql + orderBySql;

            mapList = JdbcContext.getJdbcTemplate().queryForList(selectSql);
            //列表不为空，设置跨库字段值
            if(!CollectionUtils.isEmpty(mapList)){
                //获取字段中跨库字段
                List<BmeBcFiledDTO> crossJoinList = getCrossJoin(bmeBcFiledList);
                //是否有跨库字段
                if(!CollectionUtils.isEmpty(crossJoinList)){
                    for(BmeBcFiledDTO BmeBcFiledTempDTO : crossJoinList){
                        setCrossValue(mapList,BmeBcFiledTempDTO,baseMap.get(Constants.ID).toString());
                    }

                }
            }

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(baseMap.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method findListNew OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        LOGGER.info("Class BCCRUDServiceImpl: Method findListNew: pageInfo == {}", mapList);
        return JSONResult.success(mapList);
    }

    //设置列表中的跨库字段值
    private void setCrossValue(List<Map<String, Object>> mapList, BmeBcFiledDTO bmeBcFiledTempDTO,String bcId) {
        //获取join信息
        Map<Object, Object> joinParams = new HashMap<>();
        joinParams.put("joinName",bmeBcFiledTempDTO.getFieldJoin());
        joinParams.put("pid",bcId);
        BmeBcJoinDTO bmeBcJoinDTO = bmeBcJoinDAO.getBmeBcJoinByIdName(joinParams);
        String joinMasterField = bmeBcJoinDTO.getJoinMasterField();
        String joinSlaveTable = bmeBcJoinDTO.getJoinSlaveTable();
        String joinSlaveField = bmeBcJoinDTO.getJoinSlaveField();
        String datasource = bmeBcJoinDTO.getDatasource();

        //获取主表字段值
        List<Object> masterFieldValue = getMasterFieldValue(mapList,joinMasterField);
        if(CollectionUtils.isEmpty(masterFieldValue)){
            return;
        }

        //获取跨库表字段值
        List<Map<String, Object>> slaveFieldValue = getMasterFieldValue(masterFieldValue,datasource,joinSlaveTable,joinSlaveField);
        if(CollectionUtils.isEmpty(slaveFieldValue)){
            return;
        }

        //获取跨库表字段值转map  joinSlaveFieldValue=map
        Map<Object,Map<String, Object>> crossSlaveMap = listToMap(slaveFieldValue,joinSlaveField);

        //赋值操作
        setCrossValue(mapList,crossSlaveMap,bmeBcFiledTempDTO.getField(),joinMasterField,bmeBcFiledTempDTO.getColunm());


    }

    /**
     *
     * @param mapList 数据列表
     * @param crossSlaveMap  跨库查询的数据
     * @param field 数据列表字段
     * @param joinMasterField 数据列表字段
     * @param colunm  跨库数据得字段
     */
    private void setCrossValue(List<Map<String, Object>> mapList, Map<Object, Map<String, Object>> crossSlaveMap, String field, String joinMasterField, String colunm) {
        for(Map<String, Object> mapTemp : mapList){
            Object joinMasterFieldValue;
            if(!mapTemp.containsKey(joinMasterField)){
                continue;
            }
            joinMasterFieldValue = mapTemp.get(joinMasterField);
            if(!crossSlaveMap.containsKey(joinMasterFieldValue)){
                continue;
            }
            Map<String, Object> crossSlaveMapValue = crossSlaveMap.get(joinMasterFieldValue);
            mapTemp.put(field,crossSlaveMapValue.get(colunm));
        }
    }


    /**
     *
     * @param slaveFieldValue
     * @param joinSlaveField
     * @return
     */
    private Map<Object,Map<String,Object>> listToMap(List<Map<String, Object>> slaveFieldValue,String joinSlaveField) {
        Map<Object,Map<String,Object>> mapReturn = new HashMap<>();
        for(Map<String, Object> mapTemp : slaveFieldValue){
            if(!mapTemp.containsKey(joinSlaveField)){
                continue;
            }
            mapReturn.put(mapTemp.get(joinSlaveField),mapTemp);
        }
        return mapReturn;
    }

    //获取主表字段值
    private List<Map<String,Object>> getMasterFieldValue(List<Object> masterFieldValue, String datasource, String joinSlaveTable, String joinSlaveField) {
        List<Map<String,Object>> listReturn = new ArrayList<>();
        if(CollectionUtils.isEmpty(masterFieldValue)){
            return listReturn;
        }
        String sql = " select * from  "+joinSlaveTable+" where "+joinSlaveField +" in(";
        String masterFieldValueStr = StringUtils.collectionToDelimitedString(masterFieldValue,",");
        sql = sql+masterFieldValueStr;
        sql = sql+")";
        initHandTemplate(datasource);
        listReturn = JdbcContext.getJdbcTemplate().queryForList(sql);
        return listReturn;
    }

    public static void main(String[] args) {
        System.out.println(String.format("%04d", 1));
    }

    List<Object> getMasterFieldValue(List<Map<String, Object>> mapList,String joinMasterField){
        List<Object> masterFieldValues = new ArrayList<>();
        for(Map<String, Object> map : mapList){
            masterFieldValues.add(map.get(joinMasterField));
        }
        return masterFieldValues;
    }

    //获取字段中的跨库字段 field_custom_type = CrossJoin
    private List<BmeBcFiledDTO> getCrossJoin(List<BmeBcFiledDTO> bmeBcFiledList) {
        List<BmeBcFiledDTO> crossJoinReturn = new ArrayList<>();

        if(CollectionUtils.isEmpty(bmeBcFiledList)){
            return crossJoinReturn;
        }

        for(BmeBcFiledDTO bmeBcFiledTempDTO : bmeBcFiledList){
            if("CrossJoin".equals(bmeBcFiledTempDTO.getFieldCustomType())){
                crossJoinReturn.add(bmeBcFiledTempDTO);
            }
        }
        return crossJoinReturn;
    }

    //获取字段中的跨库字段field_join值
    private List<String> getCrossJoinFieldJoin(List<BmeBcFiledDTO> bmeBcFiledList) {
        List<String> crossJoinFieldJoin = new ArrayList<>();

        if(CollectionUtils.isEmpty(bmeBcFiledList)){
            return crossJoinFieldJoin;
        }

        for(BmeBcFiledDTO bmeBcFiledTempDTO : bmeBcFiledList){
            if("CrossJoin".equals(bmeBcFiledTempDTO.getFieldCustomType())){
                crossJoinFieldJoin.add(bmeBcFiledTempDTO.getFieldJoin());
            }
        }
        return crossJoinFieldJoin;
    }

    private void getMapCondict(Map<String, Object> map, String sql, String mastTable,
                               List<Map<String, Object>> findMap,StringBuffer stringBuffer, List<Object> objectList) {
        StringBuffer stringBuffer1 = new StringBuffer();
        if (!sql.toLowerCase().contains(Constants.VALIDATEPARAM.BC_WHERE) && map.size()>0) {
            stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_6);
        }
        String field_custom_type;
        String appad;
        for (Map<String, Object> resultMap : findMap) {
            Object field = resultMap.get(Constants.VALIDATEPARAM.FIELD);
            Object clunm = resultMap.get(Constants.VALIDATEPARAM.COLUNM);
            if (map.containsKey(field)){
                if (Strings.isNullOrEmpty(stringBuffer1.toString())&& sql.lastIndexOf(Constants.VALIDATEPARAM.BC_WHERE_6) > sql.lastIndexOf(mastTable)) {
                    field_custom_type  = resultMap.get("field_custom_type").toString();
                    appad = Constants.FieldCustomType.CUSTOMTYPE_ENTITY.equalsIgnoreCase(field_custom_type) ? "T0."+clunm : resultMap.get("field_join")+"."+clunm;
                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(appad).append(" = ? ");
                    objectList.add(map.get(field));
                    if (objectList.size()==map.size()){
                        break;
                    }
                    continue;
                }
                if (!Strings.isNullOrEmpty(stringBuffer1.toString())) {
                    field_custom_type  = resultMap.get("field_custom_type").toString();
                    appad = Constants.FieldCustomType.CUSTOMTYPE_ENTITY.equalsIgnoreCase(field_custom_type) ? "T0."+clunm : resultMap.get("field_join")+"."+clunm;
                    stringBuffer1.append(appad).append(" = ? and ");
                    objectList.add(map.get(field));
                    if (objectList.size()==map.size()){
                        break;
                    }
                    continue;
                }
            }
        }
        deleteLengthSub(stringBuffer1);
        stringBuffer.append(stringBuffer1);
    }
    /**
     *
     * @param map
     * @param response
     * @throws Exception
     */
    @Override
    public void exportAutoFile(Map<String, Object> map, HttpServletResponse response) throws Exception {
        if (!map.containsKey(Constants.VALIDATEPARAM.BCCODE)){
            throw new Exception("缺失对应的bc编码");
        }
        Map bcBase = getBcBase((String) map.get(Constants.VALIDATEPARAM.BCCODE));
        if (bcBase==null || bcBase.isEmpty()){
            throw new Exception("获取对应的bc信息失败");
        }
        //先要获取对应该BC的数据字段
        List<Map<String, Object>> listFiled = findListFiled(null, bcBase);
        if (listFiled==null || listFiled.size()==0){
            throw new Exception("获取对应的bc信息失败");
        }
        //获取对应sql的数据信息
        String sql = bcBase.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
        String mastTable = bcBase.get(Constants.VALIDATEPARAM.BCTTABLE).toString();
        StringBuffer stringBuffer = new StringBuffer();
        List<Object> objectList = Lists.newArrayList();
        stringBuffer.append(sql);
        getRemoveMap(map);
        if (!map.isEmpty()){
            getMapCondict(map,sql,mastTable,listFiled,stringBuffer,objectList);
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(stringBuffer.toString(),objectList.toArray());
        if (list.isEmpty() || list.size() == 0) {
            throw new Exception("导出数据为空！");
        }
        // 创建工具类
        ExcelUtil<Object> util = new ExcelUtil<>(Object.class);
        // 导出
        String topName = DateUtil.getDateTime("yyyyMMddHHmmss");
        util.exportAutoFile(list, DateUtil.getDateTime(topName), topName, response,listFiled);
    }

    /**
     * EXCEL转PDF
     * @return
     */
    @Override
    public Map<String, Object> getPDF(Map<String, Object> map,HttpServletResponse response) throws Exception {
        Map bcBase = getBcBase((String) map.get(Constants.VALIDATEPARAM.BCCODE));
        if (bcBase==null || bcBase.isEmpty()){
            throw new Exception("获取对应的bc信息失败");
        }
        String reportBC;
        HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
        objectObjectHashMap.put("masterBcObject",bcBase);
        List<Map<String, Object>> mapListMaster = jdbcTemplate.queryForList(bcBase.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString());
        objectObjectHashMap.put("masterBcList",mapListMaster);
        Map<String, Object> reportBcMap = jdbcTemplate.queryForMap(Constants.REPORTPARAM.GET_REPORT_SEL, bcBase.get("id"));
        if (reportBcMap!=null || !reportBcMap.isEmpty()){
            //获取子BC的信息
            objectObjectHashMap.put("reportBcObject",reportBcMap);
            //判断是否有子BC的信息 如果有一起获取处理
            if (reportBcMap.get("reportbc")!=null){
                reportBC = reportBcMap.get("reportbc").toString();
                Map bcReportBase = getBcBase(reportBC);
                StringBuffer stringBuffer = new StringBuffer();
                StringBuffer stringBuffer1 = new StringBuffer();
                String slaveSQL = bcReportBase.get(Constants.VALIDATEPARAM.BC_QUERYSQL).toString();
                stringBuffer.append(slaveSQL);
                String bcTable = bcReportBase.get(Constants.VALIDATEPARAM.BCTTABLE).toString();
                stringBuffer.append(slaveSQL);
                //这里主要是判断子bc的sql语句里面是否在主表的后面有where的判断组合
                if (!slaveSQL.toLowerCase().contains(Constants.VALIDATEPARAM.BC_WHERE)) {
                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_6);
                }
                String condition="";
                if (reportBcMap.get(Constants.VALIDATEPARAM.CONDITION)!=null){
                    condition = reportBcMap.get(Constants.VALIDATEPARAM.CONDITION).toString();
                }
                if (!Strings.isNullOrEmpty(stringBuffer1.toString())&& !Strings.isNullOrEmpty(condition)){
                    stringBuffer1.append(condition);
                }else if (slaveSQL.lastIndexOf(Constants.VALIDATEPARAM.BC_WHERE_6) > slaveSQL.lastIndexOf(bcTable)&& !Strings.isNullOrEmpty(condition)){
                    stringBuffer1.append(Constants.VALIDATEPARAM.BC_WHERE_AND).append(condition);
                }
                stringBuffer.append(stringBuffer1);
                //获取子BC对应的sql和子BC的过滤条件后的sql信息
                List<Map<String, Object>> mapList = jdbcTemplate.queryForList(stringBuffer.toString());
                objectObjectHashMap.put("reportBcList",mapList);
                String tempUrl = reportBcMap.get("repdfurl").toString();
                String tempNM = reportBcMap.get("repdfnm").toString();
                //这里设置默认的信息
                /*TemplateExportParams params = new TemplateExportParams(
                        "/temp/专项支出用款申请书_map.xls");*/
                TemplateExportParams params = new TemplateExportParams(
                        tempUrl);
                //这里主要是生成对应的模板数据的excel文件
                Workbook workbook = ExcelExportUtil.exportExcel(params,objectObjectHashMap);
                String rooPath = this.getClass().getResource("/temp/").getPath();
                File savefile = new File(rooPath);
                if (!savefile.exists()) {
                    savefile.mkdirs();
                }
                String fileName =  String.valueOf(System.currentTimeMillis());
                String filedPath = fileName+Constants.REPORTPARAM.XSL;
                String pathUrl = rooPath+filedPath;
                FileOutputStream fos = new FileOutputStream(pathUrl);
                workbook.write(fos);
                fos.close();
                tempNM = tempNM+Constants.REPORTPARAM.PDF;
                ExcelToPdf.excelToPdf(tempNM,fileName,savefile,pathUrl,response);
            }
        }
        return objectObjectHashMap;
    }



    /**
     * 对最后一个字符串进行处理
     *
     * @param stringBuffer
     * @param length
     * @param split
     */
    private void deleteChar(StringBuffer stringBuffer, int length, String split, boolean istrue) {
        int selectBufferInt = stringBuffer.lastIndexOf(split);
        if (stringBuffer.length() - length == selectBufferInt) {
            if (istrue) {
                stringBuffer.deleteCharAt(selectBufferInt).append(")");
                return;
            }
            stringBuffer.deleteCharAt(selectBufferInt);
        }
    }

    /**
     * desc:方法拦截器调用之前的方法
     *
     * @param map
     * @param mapList
     * @param bcName
     * @return
     */
    public  Map inceptBefore(Map<String, Object> map, Map<String, Object> mapList, String bcName,String method) {
        HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
        MetaObjectIntercept metaObjectIntercept;
        AopContext aopContext;
        try {
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept = (MetaObjectIntercept) BeanUtils.getBean(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT).toString());
                LOGGER.info("-----------metaObjectIntercept :{}",metaObjectIntercept);
                if (metaObjectIntercept == null) {
                    new Exception("请核对拦截配置信息");
                }
                Record record = new Record();
                if (!StringUtils.isEmpty(bcName)) {
                    mapList.put(bcName, bcName);
                    record.setColumnsMap(mapList);
                    mapList.remove(bcName, bcName);
                } else {
                    record.setColumnsMap(mapList);
                }
                aopContext = new AopContext(record);
                String addBeforeMessage = "";
                switch (method){
                    case "insert": addBeforeMessage = metaObjectIntercept.addBefore(aopContext);
                        break;
                    case "update": addBeforeMessage = metaObjectIntercept.updateBefore(aopContext);
                        break;
                    case "get":  metaObjectIntercept.queryBefore(aopContext);
                        break;
                    case "findList": metaObjectIntercept.queryBefore(aopContext);
                        break;
                    case "findPageList": metaObjectIntercept.queryBefore(aopContext);
                        break;
                    case "delete": addBeforeMessage = metaObjectIntercept.deleteBefore(aopContext);
                        break;
                    default:
                }
                objectObjectHashMap.put(Constants.VALIDATEPARAM.AOP,aopContext);
                objectObjectHashMap.put(Constants.VALIDATEPARAM.INTERCEPT,metaObjectIntercept);
                if (!StringUtils.isEmpty(addBeforeMessage)) {
                    objectObjectHashMap.put("msg",addBeforeMessage);
                    return objectObjectHashMap;
                }
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method insert: e :{}", e.getMessage());
            new Exception("请核对拦截配置信息");
        }
        return objectObjectHashMap;
    }

    /**
     * desc:方法拦截器调的校验方法
     *
     * @param mapList  前段参数
     * @param list bc字段
     * @return
     */
    private String valitorInputParam(@NotNull Map<String, Object> mapList, @NotNull List<Map<String, Object>> list) {
        //String msg = "该校验方式已超出现有校验配置,请调整配置";
        String msg = null;
        for (String inParaam : mapList.keySet()) {
            if (!StringUtils.isEmpty(inParaam)) {
                for (Map<String, Object> queryMap : list) {
                    if (queryMap.get(Constants.VALIDATEPARAM.FIELD).equals(inParaam) && !StringUtils.isEmpty(queryMap.get(Constants.VALIDATEPARAM.VALIDA))) {
                        //获取需要校验的方式
                        String valiMethod = queryMap.get(Constants.VALIDATEPARAM.VALIDA).toString();
                        String va = valiMethod;
                        //对校验的方法进行加工处理
                        if (valiMethod.contains("[") || valiMethod.contains("(")) {
                            int subLegtn = valiMethod.indexOf("[");
                            valiMethod = valiMethod.substring(0, subLegtn);
                        }
                        String getMethod = ValidatorClassEnum.getDesc(valiMethod);

                        if (Strings.isNullOrEmpty(getMethod)) {
                            return msg;
                        }
                        try {
                            ValidatorService validatorService = validatorServiceMap.get(getMethod);
                            if (validatorService==null){
                                return "目前不支持该方式的校验!";
                            }
                            String msgs = validatorService.validator(va, mapList.get(inParaam), queryMap);
                            if (!Strings.isNullOrEmpty(msgs)) {
                                return msgs;
                            }
                        } catch (Exception e) {
                            msg=null;
                            JSONResult.fail(201, "参数校验失败");
                        }
                        break;
                    }

                }
            }
        }
        return msg;
    }
    /**
     * desc:方法进行入库操作时需要判断是否是自增的主键 如果是需要入库后返回对应的主键值
     *
     * @param sql
     * @param objects
     * @return
     */
    private long getInsertResultKey(@NotNull String sql,@NotNull List<Object> objects) throws Exception {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int count = JdbcContext.getJdbcTemplate().update(con -> {
            PreparedStatement ps= con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            int index = 1;
            for (Object o : objects) {
                ps.setObject(index, o);
                index = index+1;
            }
            return ps;
        }, keyHolder);
        if (count<1){
            throw new Exception("输入操作失败");
        }
        return keyHolder.getKey().longValue();
    }

    public void initHandTemplate(String dataSourceName){
        if("gengen".equals(dataSourceName)){
//            this.handTemplate = jdbcTemplate;
            JdbcContext.setJdbcTemplate(jdbcTemplate);
            return;
        }
        if("gengen_crm_base".equals(dataSourceName)){
//            this.handTemplate = gengenCrmBaseJdbcTemplate;
            JdbcContext.setJdbcTemplate(gengenCrmBaseJdbcTemplate);
            return;
        }
        if("gengen_crm_customer".equals(dataSourceName)){
//            this.handTemplate = gengenCrmCustomerJdbcTemplate;
            JdbcContext.setJdbcTemplate(gengenCrmCustomerJdbcTemplate);
            return;
        }
        if("gengen_crm_dict".equals(dataSourceName)){
//            this.handTemplate = gengenCrmDictJdbcTemplate;
            JdbcContext.setJdbcTemplate(gengenCrmDictJdbcTemplate);
            return;
        }
//        this.handTemplate = jdbcTemplate;
        JdbcContext.setJdbcTemplate(jdbcTemplate);
        return;
    }

    @Override
    public JSONResult getStatistics(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method getStatistics: map: {}", JSON.toJSON(map));
        if (map.get(Constants.VALIDATEPARAM.BCCODE) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getStatistics: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }

        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();

        //根据BC名称获取对应的BC信息
        Map baseMap = getBcBase(bcName);
        if (baseMap == null || baseMap.isEmpty()) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "", "findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {

            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", baseMap.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

            StringBuffer stringBuffer = new StringBuffer(" select ");

            //条件语句
            String stringWhere = " where 1 = 1 ";
            String condition = map.get("condition").toString();
            System.out.println(condition);
            //条件
            JSONArray conditionJsonArr = JSONObject.parseArray(map.get("condition").toString());
            String conditionSql = "";
            if (conditionJsonArr.size() > 0) {
                conditionSql = getConditionSql(conditionJsonArr, bmeBcFiledList);
            }

            // 度量类型 度量字段 measureType measureField   measureType = sum count
            JSONArray yAxisArr = JSONObject.parseArray(map.get("yAxis").toString());
            JSONArray xAxisArr = JSONObject.parseArray(map.get("xAxis").toString());
            //统计数据
            String measureSql = getYAxisSql(yAxisArr);

            //结果集sql，分组groupSql
            Map sqlMap = getXAxisSql(xAxisArr, bmeBcFiledList);

            stringBuffer.append(measureSql).append(", ").append(sqlMap.get("sql").toString());
            stringBuffer.append(" ").append("from ");
            stringBuffer.append("(").append(baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL)).append(") t ");
            if (!StringUtils.isEmpty(conditionSql)) {
                stringBuffer.append(stringWhere).append(conditionSql);
            }
            stringBuffer.append(" group by ").append(sqlMap.get("groupSql").toString());

            String orderBySql = getOrderBySql(xAxisArr);
            stringBuffer.append(" order by ").append(orderBySql);

            LOGGER.info("Class BCCRUDServiceImpl: Method getStatistics sql :{}", stringBuffer.toString());
            mapList = JdbcContext.getJdbcTemplate().queryForList(stringBuffer.toString());

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getStatistics OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        return JSONResult.success(mapList);
    }

    //封装条件字段字段
    private String getConditionSql(JSONArray conditionJsonArr, List<BmeBcFiledDTO> bmeBcFiledList) throws Exception {
        StringBuffer sql = new StringBuffer();
        for (Object object : conditionJsonArr) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if (!jsonObject.containsKey("conditionField") || !jsonObject.containsKey("conditionType") || !jsonObject.containsKey("conditionValue")) {
                continue;
            }
            String conditionField = jsonObject.get("conditionField").toString();
            String conditionType = jsonObject.get("conditionType").toString();
            String conditionValue = jsonObject.get("conditionValue").toString();

            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList,conditionField);
            if(bmeBcFiledDTO == null){
                continue;
            }
            if ("like".equals(conditionType) || "not like".equals(conditionType)) {
                sql.append(" and ").append(conditionField + " " + conditionType + " '%" + conditionValue + "%'");
            } else {
                if ("".equals(conditionValue)||"null".equals(conditionValue)) {
                    sql.append(" and (")
                            .append(conditionField + " " + conditionType + " ''")
                            .append(" or ")
                            .append(conditionField + " " + conditionType + " null)");
                } else {
                    String fieldType = bmeBcFiledDTO.getFieldType();
                    if (Constants.MYSQLTY.TIMESTAM.equals(fieldType) || Constants.MYSQLTY.DATETIME.equals(fieldType) || Constants.MYSQLTY.DATE.equals(fieldType)) {
                        String strDate = conditionValue.substring(0,10);
                        sql.append(" and ").append("date_format(" + conditionField + ", '%Y-%m-%d')").append(" " + conditionType + " '").append(strDate).append("'");
                    } else {
                        sql.append(" and ").append(conditionField).append(" " + conditionType + " '").append(conditionValue).append("'");
                    }
                }
            }
        }
        if (StringUtils.isEmpty(sql.toString())) {
            throw new Exception("条件参数设置有误，请检查");
        }
        return sql.toString();
    }

    //封装Y轴字段
    private String getYAxisSql(JSONArray yAxis) throws Exception {
        String sql = "";
        for (Object object : yAxis) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if (!jsonObject.containsKey("measureField") || !jsonObject.containsKey("measureType")) {
                continue;
            }
            String measureType = jsonObject.get("measureType").toString();
            String measureField = jsonObject.get("measureField").toString();
            if (!sql.isEmpty()) {
                sql = sql + ", ";
            }
            sql = sql + measureType + "(" + measureField + ") as y_" + measureField;
        }
        if (StringUtils.isEmpty(sql)) {
            throw new  Exception("Y轴参数设置有误，请检查");
        }
        return sql;
    }

    //封装group字段(x轴)
    private Map getXAxisSql(JSONArray xAxis, List<BmeBcFiledDTO> bmeBcFiledList) throws Exception {
        //结果集sql
        String sql = "";
        //分组sql
        String groupSql = "";
        Map map = Maps.newHashMap();
        //获取x轴度量字段及格式化字段
        for (Object object : xAxis) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if (!jsonObject.containsKey("measureField")) {
                continue;
            }
            //度量字段
            String measureField = jsonObject.get("measureField").toString();

            //格式化字段
            String formatType = "";
            if (jsonObject.containsKey("formatType")) {
                formatType = jsonObject.get("formatType").toString();
            }

            BmeBcFiledDTO bmeBcFiledDTO = getFieldMap(bmeBcFiledList, measureField);
            if (bmeBcFiledDTO == null) {
                continue;
            }

            if (!StringUtils.isEmpty(sql)) {
                sql = sql + ", ";
            }
            if (!StringUtils.isEmpty(groupSql)) {
                groupSql = groupSql + ", ";
            }

            if (!StringUtils.isEmpty(formatType)) {
                //根据bcField信息判断是否需要格式化
                String fieldType = bmeBcFiledDTO.getFieldType();
                if (Constants.MYSQLTY.TIMESTAM.equals(fieldType) || Constants.MYSQLTY.DATETIME.equals(fieldType) || Constants.MYSQLTY.DATE.equals(fieldType)) {
                    if ("year".equals(formatType)) {
                        sql = sql + "date_format(" + measureField + ", '%Y')" + " as x_" + measureField;
                        groupSql = groupSql + "date_format(" + measureField + ", '%Y')";
                    } else if ("month".equals(formatType)) {
                        sql = sql + "date_format(" + measureField + ", '%Y%m')" + " as x_" + measureField;
                        groupSql = groupSql + "date_format(" + measureField + ", '%Y%m')";
                    } else if ("day".equals(formatType)) {
                        sql = sql + "date_format(" + measureField + ", '%Y%m%d')" + " as x_" + measureField;
                        groupSql = groupSql + "date_format(" + measureField + ", '%Y%m%d')";
                    } else {
                        sql = sql + "date_format(" + measureField + ", '%Y')" + " as x_" + measureField;
                        groupSql = groupSql + "date_format(" + measureField + ", '%Y')";
                    }
                }
            } else {
                sql = sql + measureField + " as x_" + measureField;
                groupSql = groupSql + measureField;
            }
        }
        if (StringUtils.isEmpty(sql) || StringUtils.isEmpty(groupSql)) {
            throw new  Exception("X轴参数设置有误，请检查");
        }
        map.put("sql", sql);
        map.put("groupSql", groupSql);
        return map;
    }

    //排序
    private String getOrderBySql(JSONArray xAxis){
        String sql = "";
        for (Object object : xAxis) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if (!jsonObject.containsKey("measureField")) {
                continue;
            }
            String measureField = jsonObject.get("measureField").toString();
            if (!sql.isEmpty()) {
                sql = sql + ", ";
            }
            sql = sql + measureField + " asc";
        }
        return sql;
    }

    @Override
    public JSONResult getCount(Map<String, Object> map) {
        LOGGER.info("Class BCCRUDServiceImpl: Method getCount: map: {}", JSON.toJSON(map));
        if (map.get(Constants.VALIDATEPARAM.BCCODE) == null) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getCount: bcCode: ==null");
            return JSONResult.fail(201, "bc编码为空");
        }

        String bcName = map.get(Constants.VALIDATEPARAM.BCCODE).toString();

        //根据BC名称获取对应的BC信息
        Map baseMap = getBcBase(bcName);
        if (baseMap == null || baseMap.isEmpty()) {
            return JSONResult.fail(201, "bc信息为空");
        }
        initHandTemplate(baseMap.get("bc_datasource").toString());
        Map map1 = inceptBefore(baseMap, map, "", "findList");
        MetaObjectIntercept metaObjectIntercept = (MetaObjectIntercept) map1.get(Constants.VALIDATEPARAM.INTERCEPT);
        AopContext aopContext = (AopContext) map1.get(Constants.VALIDATEPARAM.AOP);

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {

            //获取bc所有的字段
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", baseMap.get(Constants.ID));
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);

            StringBuffer stringBuffer = new StringBuffer(" select ");

            //条件语句
            String stringWhere = " where 1 = 1 ";
            String condition = map.get("condition").toString();
            System.out.println(condition);
            //条件
            JSONArray conditionJsonArr = JSONObject.parseArray(map.get("condition").toString());
            String conditionSql = "";
            if (conditionJsonArr.size() > 0) {
                conditionSql = getConditionSql(conditionJsonArr, bmeBcFiledList);
            }

            // 统计字段
            JSONArray axisArr = JSONObject.parseArray(map.get("axis").toString());
            String axisSql = getAxisSql(axisArr);
            stringBuffer.append(axisSql);
            stringBuffer.append(" ").append("from ");
            stringBuffer.append("(").append(baseMap.get(Constants.VALIDATEPARAM.BC_QUERYSQL)).append(") t ");
            if (!StringUtils.isEmpty(conditionSql)) {
                stringBuffer.append(stringWhere).append(conditionSql);
            }

            LOGGER.info("Class BCCRUDServiceImpl: Method getCount sql :{}", stringBuffer.toString());
            mapList = JdbcContext.getJdbcTemplate().queryForList(stringBuffer.toString());

            //对拦截器进行添加参数
            if (!StringUtils.isEmpty(map.get(Constants.VALIDATEPARAM.BC_INTERCEPT))) {
                metaObjectIntercept.queryAfter(aopContext);
            }
        } catch (Exception e) {
            LOGGER.error("Class BCCRUDServiceImpl: Method getCount OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, e.getMessage());
        }
        return JSONResult.success(mapList);
    }

    //统计字段处理
    private String getAxisSql(JSONArray axis) throws Exception {
        String sql = "";
        for (Object object : axis) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if (!jsonObject.containsKey("measureField") || !jsonObject.containsKey("measureType")) {
                continue;
            }
            String measureField = jsonObject.get("measureField").toString();
            String measureType = jsonObject.get("measureType").toString();
            if (!sql.isEmpty()) {
                sql = sql + ", ";
            }
            sql = sql + measureType + "(" + measureField + ") as " + measureField;
        }
        if (StringUtils.isEmpty(sql)) {
            throw new  Exception("Y轴参数设置有误，请检查");
        }
        return sql;
    }
}
